学习laravel源码之中间件原理

刨析laravel源码之中间件原理

在看了laravel关于中间件的源码和参考了相关的书籍之后,写了一个比较简陋的管道和闭包实现,代码比较简单,但是却不好理解所以还是需要多写多思考才能想明白其中的意义。代码如下,权当自己的笔记吧。

管道实现

interface Pipeline
{
    public function go();
}

class Animal implements Pipeline
{
    protected $name;
    public function __construct($name)
    {
        $this->name = $name;
    }
    public function go()
    {
       echo $this->name.PHP_EOL;
    }

}

class Cat extends Animal
{
    protected $pip;
    public function __construct(Pipeline $pip)
    {   
        $this->pip = $pip;
    }
    public function go()
    {
        echo __CLASS__.PHP_EOL;
        $this->pip->go();
    }
}

class Dog extends Animal
{
     protected $pip;
    public function __construct(Pipeline $pip)
    {   
        $this->pip = $pip;
    }
    public function go()
    {
        echo __CLASS__.PHP_EOL;        
        $this->pip->go();
        echo "呵呵哒";
    }
}

$animal =  new Animal("Tom");
$cat = new Cat($animal);
$dog = new Dog($cat);
$dog->go();

执行结果:
Dog
Cat
Tom
呵呵哒

闭包实现

interface Middleware
{
    public static function echoName(Closure $next);
}

class BeforeMiddleware implements Middleware
{
    public static function echoName(Closure $next)
    {
        echo "before".PHP_EOL;
        $next();
        echo "after".PHP_EOL;
    }
}

function Func($func,$className)
{
    if($func instanceof $func){
        return function() use($func,$className){
            return $className::echoName($func); 
        };
    }
}

$objs = ['BeforeMiddleware'];
$func = function(){echo "test code".PHP_EOL;};
$go = array_reduce($objs,"Func",$func);
$go();

输出结果为:
before
test code
after

关于中间件这部分的设计模式,主要还是用到的装饰器模式,但是使用的却很灵活,所以还是要多使用,才能真正的吃透这块。
代码写的很简单,但是这只是一个跳板,理解这部分之后再去观看关于中间件部分就会更好的理解了。

posted @ 2018-04-18 00:37  秦至臻  阅读(175)  评论(0编辑  收藏  举报