Laravel服务容器中的Tagging

PHP Laravel

此文章为作者原创。未经允许,不得用于商业用途。

自己学Tagging这个知识点的时候在国外的网站看到一个挺好的解释

Being able to resolve bindings from the container is pretty important. Normally we can only resolve something if we know how it's been bound to the container. With Laravel 5, we're now able to tag our bindings so that developers can easily resolve all bindings that have the same tag.

相信读者的英语水平不会很差,这段话还是能看得懂的。其实这段话说的就是从Laravel5.0开始,Laravel提供的Tagging能给服务器绑定打上“标签”,然后在解析的时候一次能解析具有相同标签的多个绑定(当然你觉得好玩也可以给一个绑定打上标签……)

我们来写一个简单的例子

BMW.php

<?php
namespace App\Demos;

class BMW {
	public function drive(){
		echo "I drive BMW";
	}
}
?>

Benz.php

<?php
namespace App\Demos;

class Benz {
	public function drive(){
		echo "I drive Benz";
	}
}
?>

创建CarServiceProvider并注册,然后Tagging如下

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Demos\BMW;
use App\Demos\Benz;

class CarServiceProvider extends ServiceProvider
{
    public function boot()
    {
        //
    }
    public function register()
    {
        $this->app->singleton('bmw',function(){
            return new BMW();
        });

         $this->app->singleton('benz',function(){
            return new Benz();
        });

        $this->app->tag(['bmw','benz'],'car');  //给bmw和benz绑定打上"car"的标签
    }
}

创建测试控制器CarController并编辑

php artisan make:controller CarController

CarController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App;

class CarController extends Controller
{
    public function index(){
    	$cars = App::tagged('car');
    	foreach ($cars as $c) {
    		$c->drive();
    	}
    }
}

注册路由

Route::any('/car','CarController@index');

这时访问localhost/your projectName/public/car将会输出"I drive BMW I drive Benz"。


Huas Leung
程序员/web开发者
Light up my life!

分享到: