Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Service Container - Passing ordinary arguments to service constructor

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 ?

like image 898
Rafael Adel Avatar asked Oct 02 '13 17:10

Rafael Adel


Video Answer


1 Answers

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);
like image 173
Cerad Avatar answered Sep 19 '22 19:09

Cerad