8

我有这个Paginator类构造函数:

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

Paginator服务的注册Ibw/JobeetBundle/Resources/config/services.yml方式如下:

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

services:
    ibw_jobeet_paginator:
        class: %ibw_jobeet_paginator.class%

当我使用Paginator这样的:

$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);

我得到这个例外:

警告:缺少 Ibw\JobeetBundle\Utils\Paginator::__construct() 的参数 1,在第 1306 行的 /var/www/jobeet/app/cache/dev/appDevDebugProjectContainer.php 中调用并在 /var/www/jobeet/ 中定义src/Ibw/JobeetBundle/Utils/Paginator.php 第 13 行

我想将参数传递给Paginator服务构造函数时有问题。你能告诉我,如何将参数传递给服务构造函数吗?

4

1 回答 1

23

好吧,要回答您的问题,您可以使用 arguments 参数传递服务构造函数参数:

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

当然,由于参数是动态的,因此这并不能真正帮助您。

相反,将参数从构造函数移动到另一个方法:

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);
于 2013-10-02T19:33:03.480 回答