Symfony 2 依赖注入 参数

  • 发布时间 2015-02-02
  • 分类 php

Service Parameters(服务参数)

namespace Kittencup\Di;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

include "vendor/autoload.php";

class Article
{

    protected $title;
    protected $content;
    protected $id;

    public function __construct($id,Db $db)
    {
        $data = $db->findArticle($id);
        $this->id = $id;
        $this->title = $data['title'];
        $this->content = $data['content'];
    }

}

class Db
{
    public function findArticle($id)
    {
        return [
            'title' => 'kittencup',
            'content' => 'kittencup.com'
        ];
    }
}

$container = new ContainerBuilder();

$container->setParameter('id', 100);

$container->register('db', 'Kittencup\Di\Db');

$container->register('article', 'Kittencup\Di\Article')
    ->addArgument('%id%')
    ->addArgument(new Reference('db'));

$article = $container->get('article');

在初始化Article类时需要用的$id,可以通过setParameter()方法将其注册进Container,在需要时使用"%名字%"的格式就可以调用

Array Parameters(数组参数)


$container->setParameter('xxxx', array('1', '2', '3'));

Constants as Parameters(常量作为参数)


$container->setParameter('xxxx', GLOBAL_CONSTANT);