Slim 框架学习,第一天

来源:互联网 发布:手机辅助软件 编辑:程序博客网 时间:2024/06/05 05:52

index.php 分析


index 文件初识,分析每个语句背后含义。

    require 'vendor/autoload.php'; //引入自动载入类,使用的是spl_register()    $app = new Slim\App(); //实例化App对象    $app->get('/hello/{name}',function($request,$response,$args){        return $response->write("Hello," . $args['name']);    }); //发送一个get请求    $app->run();

详细分析

require ‘vendor/autoload.php’;

主要利用是利用spl_autoload_register 自动载入所需要的类。该方法,将在后面做专题讲述

$app = new Slim\App();

主要是实例化了App类,代码如下

    public function __construct($container = [])    {        if (is_array($container)) {            $container = new Container($container);        }        if (!$container instanceof ContainerInterface) {            throw new InvalidArgumentException('Expected a ContainerInterface');        }        $this->container = $container;    }
  • 从上面可以看出,在实例化App类的时候,主要实例化了Container 对象,并作为作为一个属性,保存在了App 对象中
  • 注意,此时的是App对象是以psr7 模式实现的即(值对象)

    $app->get()分析

    设置一个路由,并注册到容器当中
    具体包含以下两段代码

 public function get($pattern, $callable) {    return $this->map(['GET'], $pattern, $callable); }
public function map(array $methods, $pattern, $callable){        if ($callable instanceof Closure) {            $callable = $callable->bindTo($this->container);  //Closure::bindTo — 复制当前闭包对象,绑定指定的$this对象和类作用域。        }        $route = $this->container->get('router')->map($methods, $pattern, $callable);        if (is_callable([$route, 'setContainer'])) {            $route->setContainer($this->container);        }        if (is_callable([$route, 'setOutputBuffering'])) {            $route->setOutputBuffering($this->container->get('settings')['outputBuffering']);        }        return $route;    }

#### 重点注意以下:

 if ($callable instanceof Closure) {            $callable = $callable->bindTo($this->container);  //Closure::bindTo — 复制当前闭包对象,绑定指定的$this对象和类作用域。        }

今天先到这里,明天继续