學習Slim Framework for PHP v3 (1)

來源:互聯網
上載者:User
學習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是個什麼東西呢,來看代碼:

  

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;}

  來看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都加到這個裡面就好了。

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

  第一次寫,就先這樣吧。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.