thapp / iocconf
使用xml进行ioc容器配置
v1.0.1
2013-04-30 10:26 UTC
Requires
- thapp/xmlconf: 1.0.*
Requires (Dev)
- mockery/mockery: 0.7.2
This package is not auto-updated.
Last update: 2024-09-23 11:29:45 UTC
README
概要
IoCConf提供了一种方便的方式,使用xml处理依赖注入。例如,可以使用构造函数或setter注入来设置控制器。
安装
IocConf需要XmlConf才能运行。
将thapp/iocconf和thapp/xmlconf添加到composer.json的要求中
{ "require": { "thapp/iocconf": "1.0.*", "thapp/xmlconf": "1.0.*" } }
然后运行composer update
或composer install
下一步是告诉Laravel加载serviceprovider。在app/config/app.php
中添加
// ... 'Thapp\IocConf\IocConfServiceProvider' // ...
到providers
数组。
确保XmlConf安装正确,然后告诉XmlConf在哪里找到ioc配置(app/config/packages/thapp/xmlconf/config.php
)
return array( /* |-------------------------------------------------------------------------- | Basedir relative to the install directory |-------------------------------------------------------------------------- */ 'basedir' => array( 'ioc' => 'vendor/thapp/iocconf/src/Thapp/IocConf' ), /* |-------------------------------------------------------------------------- | Reader dictionary |-------------------------------------------------------------------------- */ 'namespaces' => array( 'ioc' => 'Thapp\\IocConf' ), );
示例
假设你想要将Laravel的视图对象注入到控制器中,xml配置可能看起来像这样
<?php namespace Acme; use \BaseController; class FrontController extends BaseController { // ... setter method on your controller public function setView(\Illuminate\View\Environment $view) { $this->view = $view; } }
配置xml可能看起来像这样
<container xmlns="http://getsymphony.com/schema/ioc"> <entities> <entity class="Acme\FrontController" scope="prototype"/> <!-- the controller has a setter method for setting the view object --> <call method="setView"> <argument id="view"/> </call> </entity> </entities> </container>
用法
xml
注意:实体节点可以有一个id属性,但必须有class和scope属性,参数节点必须具有id或class属性。
可能的实体作用域
- prototype // see Container::bind();
- singleton // see Container::singleton();
- shared // see Container::share();
<?xml version="1.0" encoding="UTF-8"?> <container xmlns="http://getsymphony.com/schema/ioc"> <entities> <entity id="acme.frontcontroller" class="FrontController" scope="prototype"/> <entity id="acme.admincontroller" class="AdminController" scope="prototype"> <call method="setView"> <argument id="view"/> </call> </entity> <entity class="ControllerRepository" scope="singleton"> <argument id="acme.frontcontroller"/> <argument id="acme.admincontroller"/> </entity> </entities> </container>
php
$repo = App::make('ControllerRepository'); $repo2 = App::make('ControllerRepository'); $repo === $repo2 // true