首頁 >後端開發 >php教程 >学习Slim Framework for PHP v3 (1)

学习Slim Framework for PHP v3 (1)

WBOY
WBOY原創
2016-06-13 12:28:291185瀏覽

学习Slim Framework for PHP v3 (一)

  因为公司的项目用到是slim 框架,所以想把它学习一下。在公司用到是Slim2版本,现在官网已经到达 Slim3的版本了。官网地址:http://www.cnblogs.com/lmenglliren89php/。

  首先按照官网的教程,安装Slim:

    1.curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

    2.composer require slim/slim "^3.0"

  这样一个Slim就安装好了。还有Apache的DirectDocumentroot设置:AllowOverride All。

  同时它自带的Example的例子也是可以运行的,需要调整下文件夹的位置就好。

  

  如何才能理解一个框架呢?是很顺利的使用吗?还是从一步步去跟进去它的流程?

 

  我的思路是这样的,我把这个Example改成自己的项目,然后在不知道如何去的时候去深挖一下,不知道这样的逻辑是否正确,暂且就这样做吧。

  项目逻辑要求是这样的,页面提交数据--->>接收数据--->>存入数据库--->>记入日志--->>返回写入成功

  接收数据的route:

    

$app->get('/replace/', function ($request, $response, $args) {         Example\Module\Replace::instance()->setBody($request, $response);    });

  

 

  要说的是Slim就是基于route概念的,它将所有的request都转给不同的route,然后每个route完成功能,最后设定response,请求完毕。

  get方法就是去设定一个route,以后的‘replace’就会匹配到那个闭包函数中。

  

  而这个route是放在哪里呢?在APP.php中有个contianer。这个container是个什么东西呢,来看代码:

  

<span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> __construct(<span style="color: #800080;">$container</span> =<span style="color: #000000;"> []){    </span><span style="color: #0000ff;">if</span> (<span style="color: #008080;">is_array</span>(<span style="color: #800080;">$container</span><span style="color: #000000;">)) {        </span><span style="color: #800080;">$container</span> = <span style="color: #0000ff;">new</span> Container(<span style="color: #800080;">$container</span><span style="color: #000000;">);    }    </span><span style="color: #0000ff;">if</span> (!<span style="color: #800080;">$container</span><span style="color: #000000;"> instanceof ContainerInterface) {        </span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> InvalidArgumentException('Expected a ContainerInterface'<span style="color: #000000;">);    }    </span><span style="color: #800080;">$this</span>->container = <span style="color: #800080;">$container</span><span style="color: #000000;">;}</span>

  来看Container怎么做的:

public function __construct(array $values = []){    parent::__construct($values);    $userSettings = isset($values['settings']) ? $values['settings'] : [];    $this->registerDefaultServices($userSettings);}private function registerDefaultServices($userSettings){    $defaultSettings = $this->defaultSettings;    /**     * This service MUST return an array or an     * instance of \ArrayAccess.     *     * @return array|\ArrayAccess     */    $this['settings'] = function () use ($userSettings, $defaultSettings) {        return new Collection(array_merge($defaultSettings, $userSettings));    };    if (!isset($this['environment'])) {        /**         * This service MUST return a shared instance         * of \Slim\Interfaces\Http\EnvironmentInterface.         *         * @return EnvironmentInterface         */        $this['environment'] = function () {            return new Environment($_SERVER);        };    }    if (!isset($this['request'])) {        /**         * PSR-7 Request object         *         * @param Container $c         *         * @return ServerRequestInterface         */        $this['request'] = function ($c) {            return Request::createFromEnvironment($c->get('environment'));        };    }    if (!isset($this['response'])) {        /**         * PSR-7 Response object         *         * @param Container $c         *         * @return ResponseInterface         */        $this['response'] = function ($c) {            $headers = new Headers(['Content-Type' => 'text/html; charset=UTF-8']);            $response = new Response(200, $headers);            return $response->withProtocolVersion($c->get('settings')['httpVersion']);        };    }    if (!isset($this['router'])) {        /**         * This service MUST return a SHARED instance         * of \Slim\Interfaces\RouterInterface.         *         * @return RouterInterface         */        $this['router'] = function () {            return new Router;        };    }    if (!isset($this['foundHandler'])) {        /**         * This service MUST return a SHARED instance         * of \Slim\Interfaces\InvocationStrategyInterface.         *         * @return InvocationStrategyInterface         */        $this['foundHandler'] = function () {            return new RequestResponse;        };    }    if (!isset($this['errorHandler'])) {        /**         * This service MUST return a callable         * that accepts three arguments:         *         * 1. Instance of \Psr\Http\Message\ServerRequestInterface         * 2. Instance of \Psr\Http\Message\ResponseInterface         * 3. Instance of \Exception         *         * The callable MUST return an instance of         * \Psr\Http\Message\ResponseInterface.         *         * @param Container $c         *         * @return callable         */        $this['errorHandler'] = function ($c) {            return new Error($c->get('settings')['displayErrorDetails']);        };    }    if (!isset($this['notFoundHandler'])) {        /**         * This service MUST return a callable         * that accepts two arguments:         *         * 1. Instance of \Psr\Http\Message\ServerRequestInterface         * 2. Instance of \Psr\Http\Message\ResponseInterface         *         * The callable MUST return an instance of         * \Psr\Http\Message\ResponseInterface.         *         * @return callable         */        $this['notFoundHandler'] = function () {            return new NotFound;        };    }    if (!isset($this['notAllowedHandler'])) {        /**         * This service MUST return a callable         * that accepts three arguments:         *         * 1. Instance of \Psr\Http\Message\ServerRequestInterface         * 2. Instance of \Psr\Http\Message\ResponseInterface         * 3. Array of allowed HTTP methods         *         * The callable MUST return an instance of         * \Psr\Http\Message\ResponseInterface.         *         * @return callable         */        $this['notAllowedHandler'] = function () {            return new NotAllowed;        };    }    if (!isset($this['callableResolver'])) {        /**         * Instance of \Slim\Interfaces\CallableResolverInterface         *         * @param Container $c         *         * @return CallableResolverInterface         */        $this['callableResolver'] = function ($c) {            return new CallableResolver($c);        };    }}

  会看到这段代码就是初始化container中的router key,以后的route都加到这个里面就好了。

<strong> $this['router'] = function () {   return new Router; };<br /> <br /> </strong> 只是能不加入自己的Key呢?<strong><br /></strong>

  第一次写,就先这样吧。

 

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn