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

前端之家收集整理的这篇文章主要介绍了php – Symfony2服务容器 – 将普通参数传递给服务构造函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个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,$current_page);

我得到这个例外:

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

我猜在向Paginator服务构造函数传递参数时出现了问题.你能告诉我,如何将参数传递给服务构造函数

好吧,要回答你的问题,你使用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,$current_page)
    {
    }
}

$paginator = $this->get('ibw_jobeet_paginator')->init($total_jobs,$current_page);
原文链接:https://www.f2er.com/php/139086.html

猜你在找的PHP相关文章