Home Backend Development PHP Tutorial 学习Slim Framework for PHP v3 (1)

学习Slim Framework for PHP v3 (1)

Jun 13, 2016 pm 12:28 PM
function return this

学习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);    });
Copy after login

  

  要说的是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>
Copy after login

  来看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);        };    }}
Copy after login

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

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

  第一次写,就先这样吧。

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

What is the execution order of return and finally statements in Java? What is the execution order of return and finally statements in Java? Apr 25, 2023 pm 07:55 PM

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

What is the purpose of the 'enumerate()' function in Python? What is the purpose of the 'enumerate()' function in Python? Sep 01, 2023 am 11:29 AM

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

Detailed explanation of the role and function of the MySQL.proc table Detailed explanation of the role and function of the MySQL.proc table Mar 16, 2024 am 09:03 AM

Detailed explanation of the role and function of the MySQL.proc table. MySQL is a popular relational database management system. When developers use MySQL, they often involve the creation and management of stored procedures (StoredProcedure). The MySQL.proc table is a very important system table. It stores information related to all stored procedures in the database, including the name, definition, parameters, etc. of the stored procedures. In this article, we will explain in detail the role and functionality of the MySQL.proc table

How does Vue3 use setup syntax sugar to refuse to write return How does Vue3 use setup syntax sugar to refuse to write return May 12, 2023 pm 06:34 PM

Vue3.2 setup syntax sugar is a compile-time syntax sugar that uses the combined API in a single file component (SFC) to solve the cumbersome setup in Vue3.0. The declared variables, functions, and content introduced by import are exposed through return, so that they can be used in Vue3.0. Problems in use 1. There is no need to return declared variables, functions and content introduced by import during use. You can use syntactic sugar //import the content introduced import{getToday}from'./utils'//variable constmsg='Hello !'//function func

Let's talk about why Vue2 can access properties in various options through this Let's talk about why Vue2 can access properties in various options through this Dec 08, 2022 pm 08:22 PM

This article will help you interpret the vue source code and introduce why you can use this to access properties in various options in Vue2. I hope it will be helpful to everyone!

Use the return keyword in JavaScript Use the return keyword in JavaScript Feb 18, 2024 pm 12:45 PM

Usage of return in JavaScript requires specific code examples In JavaScript, the return statement is used to specify the value returned from a function. Not only can it be used to end the execution of a function, it can also return a value to the place where the function was called. The return statement has the following common uses: Return a value The return statement can be used to return a value to the place where the function is called. Here is a simple example: functionadd(a,b){

See all articles