简体   繁体   English

Symfony2服务容器 - 将普通参数传递给服务构造函数

[英]Symfony2 Service Container - Passing ordinary arguments to service constructor

I have this Paginator class constructor: 我有这个Paginator类构造函数:

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 : 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%

When i use the Paginator like this: 当我像这样使用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);

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 警告:缺少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行

I guess there's something wrong in passing arguments to the Paginator service constructor. 我猜在向Paginator服务构造函数传递参数时出现了Paginator Could you tell me, How to pass arguments to a service constructor ? 你能告诉我,如何将参数传递给服务构造函数?

Well, to answer your question, you pass service constructor arguments using the arguments parameter: 好吧,要回答你的问题,你使用arguments参数传递服务构造函数参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM