Symfony2 Service Container - Passing ordinary arguments to service constructor

10,803

Well, to answer your question, you pass service constructor arguments using the arguments parameter:

services:
    ibw_jobeet_paginator:
        class: %ibw_jobeet_paginator.class%
    arguments:
        - 1 # total
        - 2 # per page
        - 3 # current page

Of course that does not really help you out much since the parameters are dynamic.

Instead, move the arguments from the constructor to another method:

class Paginator
{    
    public function __construct() {}

    public function init($total_count, $per_page, $current_page)
    {
    }
}

$paginator = $this->get('ibw_jobeet_paginator')->init($total_jobs, $per_page, $current_page);
Share:
10,803
Rafael Adel
Author by

Rafael Adel

About me

Updated on July 28, 2022

Comments

  • Rafael Adel
    Rafael Adel almost 2 years

    I have this Paginator class constructor:

    class Paginator
    {    
        public function __construct($total_count, $per_page, $current_page)
        {
        }
    }
    

    The Paginator Service is registered in Ibw/JobeetBundle/Resources/config/services.yml like this :

    parameters:
        ibw_jobeet_paginator.class: Ibw\JobeetBundle\Utils\Paginator
    
    services:
        ibw_jobeet_paginator:
            class: %ibw_jobeet_paginator.class%
    

    When i use the Paginator like this:

    $em = $this->getDoctrine()->getManager();
    
    $total_jobs = $em->getRepository('IbwJobeetBundle:Job')->getJobsCount($id);
    $per_page = $this->container->getParameter('max_jobs_on_category');
    $current_page = $page; 
    
    $paginator = $this->get('ibw_jobeet_paginator')->call($total_jobs, $per_page, $current_page);
    

    I get this exception:

    Warning: Missing argument 1 for Ibw\JobeetBundle\Utils\Paginator::__construct(), called in /var/www/jobeet/app/cache/dev/appDevDebugProjectContainer.php on line 1306 and defined in /var/www/jobeet/src/Ibw/JobeetBundle/Utils/Paginator.php line 13

    I guess there's something wrong in passing arguments to the Paginator service constructor. Could you tell me, How to pass arguments to a service constructor ?

  • Rafael Adel
    Rafael Adel over 10 years
    Yea, I did that just to get it working, But having the ability to pass the arguments inside $this->get() method would be great.