看了一些介绍,感觉都说得不够透彻啊。我个人简单举个例子,就是在搜索的时候,把所有可变条件都作为参数输入,这样可以实现代码最大程度的复用,增加代码的扩展性。不过,YII框架这种情况提供了其他相应的方案,先看看容器方式的实现。
说实话,我自己没看很懂,半知半觉,以后花时间好好研究一下,我怎么感觉这都不像php了,可能是因为没有接触过重型框架
容器 定义并解决依赖关系
namespace app\controllers;
use yii\web\Controller;
use yii\di\Container;
class HelloController extends Controller{
public function actionAbout(){
$container = new Container;
$container->set('app\controllers\Driver', 'app\controllers\ManDriver');
$car = $container -> get('app\controllers\Car');
$car->run();
}
}
interface Driver{
public function drive();
}
class ManDriver implements Driver{
public function drive(){
echo 'i am an old man!';
}
}
class Car{
private $driver = null;
public function __construct(Driver $driver){
$this->driver = $driver;
}
public function run(){
$this->driver->drive();
}
}
服务定位器 配置服务的参数信息
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\di\ServiceLocator;
class HelloController extends Controller{
public function actionAbout(){
\yii::$container->set('app\controllers\Driver', 'app\controllers\ManDriver') ;
$sl = new ServiceLocator;
$sl -> set('car',[
'class' => 'app\controllers\Car'
]);//这一段可以加到web.php 然后通过$app->car实现
$car = $sl->get('car');
$car->run();
}
}
interface Driver{
public function drive();
}
class ManDriver implements Driver{
public function drive(){
echo 'i am an old man1!';
}
}
class Car{
private $driver = null;
public function __construct(Driver $driver){
$this->driver = $driver;
}
public function run(){
$this->driver->drive();
}
}
没有碰到实际工程的话,并看不出来这种方法的奇妙。以后碰到问题再补充。