SlimPHP開發指南一:導引(中英對照)

靜好先生發表於2019-04-02

Get Started (開始)

Home(簡介)

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs. At its core, Slim is a dispatcher that receives an HTTP request, invokes an appropriate callback routine, and returns an HTTP response. That’s it.

Slim是一個PHP微框架,可以幫助您快速編寫簡單但功能強大的web應用程式和api。Slim的核心是一個dispatcher(排程器),它接收HTTP請求,呼叫適當的回撥例程,並返回HTTP響應。就是這樣。

What’s the point?(有什麼意義?)

Slim is an ideal tool to create APIs that consume, repurpose, or publish data. Slim is also a great tool for rapid prototyping. Heck, you can even build full-featured web applications with user interfaces. More importantly, Slim is super fast and has very little code. In fact, you can read and understand its source code in only an afternoon!

Slim是消費、重用或釋出資料的理想API工具。Slim也是快速原型製作的一個很好的工具。見鬼,您甚至可以使用使用者介面構建功能齊全的web應用程式。更重要的是,Slim速度非常快,程式碼很少。事實上,您只需一個下午就可以閱讀和理解它的原始碼!

You don’t always need a kitchen-sink solution like Symfony or Laravel. These are great tools, for sure. But they are often overkill. Instead, Slim provides only a minimal set of tools that do what you need and nothing else.

你並不總是需要像Symfony或Laravel那麼激進的解決方案。毫無疑問,這些都是很棒的工具。但它們往往是矯枉過正。相反,Slim只提供了一組最小的工具,它們只做您需要的事情,而不做其他任何事情。

How does it work?(如何工作?)

First, you need a web server like Nginx or Apache. You should configure your web server so that it sends all appropriate requests to one “front-controller” PHP file. You instantiate and run your Slim app in this PHP file.

A Slim app contains routes that respond to specific HTTP requests. Each route invokes a callback and returns an HTTP response. To get started, you first instantiate and configure the Slim application. Next, you define your application routes. Finally, you run the Slim application. It’s that easy. Here’s an example application:

首先,您需要像Nginx或Apache這樣的web伺服器。您應該配置您的web伺服器,以便它將所有適當的請求傳送到一個“前端控制器”PHP檔案。在這個PHP檔案中例項化並執行Slim應用程式。

slim應用程式包含響應特定HTTP請求的路由。每個路由呼叫一個回撥並返回一個HTTP響應。首先,您要例項化並配置Slim應用程式。接下來,定義應用程式路由。最後,執行Slim應用程式。它是那麼容易。下面是一個應用程式示例:

<?php
// Create and configure Slim app
$config = ['settings' => [
    'addContentLengthHeader' => false,
]];
$app = new \Slim\App($config);

// Define app routes
$app->get('/hello/{name}', function ($request, $response, $args) {
    return $response->write("Hello " . $args['name']);
});

// Run app
$app->run();
複製程式碼

Request and response(請求和相應)

When you build a Slim app, you are often working directly with Request and Response objects. These objects represent the actual HTTP request received by the web server and the eventual HTTP response returned to the client.

Every Slim app route is given the current Request and Response objects as arguments to its callback routine. These objects implement the popular PSR 7 interfaces. The Slim app route can inspect or manipulate these objects as necessary. Ultimately, each Slim app route MUST return a PSR 7 Response object.

當您構建一個Slim應用程式時,您經常直接處理請求和響應物件。這些物件表示web伺服器接收到的實際HTTP請求和返回給客戶機的最終HTTP響應。

每個Slim應用程式路由都將當前請求和響應物件作為其回撥例程的引數。這些物件實現了流行的PSR 7介面。Slim應用程式路由可以根據需要檢查或操作這些物件。最終,每個Slim應用程式路由必須返回一個PSR 7響應物件。

Bring your own components(引入自己的元件)

Slim is designed to play well with other PHP components, too. You can register additional first-party components such as Slim-Csrf, Slim-HttpCache, or Slim-Flash that build upon Slim’s default functionality. It’s also easy to integrate third-party components found on Packagist.

Slim還可以很好地與其他PHP元件配合使用。您可以額外註冊基於Slim預設功能的自有元件,如Slim-csrf、Slim-httpcache或Slim-flash。或者整合Packagist上的第三方元件也很容易。

How to read this documentation?(如何閱讀此文件)

If you are new to Slim, I recommend you read this documentation from start to finish. If you are already familiar with Slim, you can instead jump straight to the appropriate section.

如果您是Slim的新手,我建議您從頭到尾閱讀本文。如果您已經熟悉Slim,則可以直接跳到相應的部分。

This documentation begins by explaining Slim’s concepts and architecture before venturing into specific topics like request and response handling, routing, and error handling.

本文件首先解釋Slim的概念和體系結構,然後討論請求和響應處理、路由和錯誤處理等特定主題。

Installation(安裝)

System Requirements

Web server with URL rewriting
PHP 5.5 or newer
複製程式碼

How to Install Slim

We recommend you install Slim with Composer. Navigate into your project’s root directory and execute the bash command shown below. This command downloads the Slim Framework and its third-party dependencies into your project’s vendor/ directory.

我們建議您使用Composer安裝Slim。導航到專案的根目錄並執行如下所示的bash命令。此命令將Slim框架及其第三方依賴項下載到專案的vendor/目錄中。

composer require slim/slim "^3.0"
複製程式碼

Require the Composer autoloader into your PHP script, and you are ready to start using Slim.

<?php
require 'vendor/autoload.php';
複製程式碼

Upgrade Guide(升級指南)

New PHP version
Slim 3 requires PHP 5.5+
複製程式碼

Class \Slim\Slim renamed \Slim\App

Slim 3 uses \Slim\App for the Application object usually named $app.

$app = new \Slim\App();
複製程式碼

New Route Function Signature(新的路由函式特徵)

$app->get('/', function (Request $req,  Response $res, $args = []) {
    return $res->withStatus(400)->write('Bad Request');
});
複製程式碼

Request and response objects are no longer accessible via the Application object

請求和響應物件不再可以通過應用程式物件訪問

As mentioned above, Slim 3 passes the Request and Response objects as arguments to the route handling function. Since they are now accessible directly in the body of a route function, request and response are no longer properties of the /Slim/App (Application object) instance.

如上所述,Slim 3將請求和響應物件作為引數傳遞給路由處理函式。由於它們現在可以在route函式體中直接訪問,請求和響應不再是/Slim/App(應用程式物件)例項的屬性。

Getting _GET and _POST variables(獲取_GET和_POST變數)

$app->get('/', function (Request $req,  Response $res, $args = []) {
    $myvar1 = $req->getParam('myvar'); //checks both _GET and _POST [NOT PSR-7 Compliant]
    $myvar2 = $req->getParsedBody()['myvar']; //checks _POST  [IS PSR-7 compliant]
    $myvar3 = $req->getQueryParams()['myvar']; //checks _GET [IS PSR-7 compliant]
});
複製程式碼

Hooks(鉤子)

Hooks are no longer part of Slim as of v3. You should consider reimplementing any functionality associated with the default hooks in Slim v2 as middleware instead. If you need the ability to apply custom hooks at arbitrary points in your code (for example, within a route), you should consider a third-party package such as Symfony’s EventDispatcher or Zend Framework’s EventManager.

鉤子在v3中不再是Slim的一部分。您應該考慮將Slim v2中與預設鉤子相關的任何功能重新實現為中介軟體。如果您需要在程式碼中的任意點應用自定義鉤子的能力(例如,在路由中),您應該考慮第三方包,如Symfony的EventDispatcher或Zend Framework的EventManager。

Removal HTTP Cache(遷移HTTP快取)

In Slim v3 we have removed the HTTP-Caching into its own module Slim\Http\Cache.

在Slim v3中,我們已經將Http快取遷移到它自己的模組Slim\Http\Cache中。

Removal of Stop/Halt

Slim Core has removed Stop/Halt. In your applications, you should transition to using the withStatus() and withBody() methods.

Slim核心已刪除Stop/Halt。在應用程式中,應該過渡到使用withStatus()和withBody()方法。

Removal of autoloader(取消自動裝載器)

為什麼有些框架越來越複雜,因為裡面充斥著過時的程式碼,混淆了開發者,及時清理很重要,保持簡單,避免出現重複的輪子

Slim::registerAutoloader() have been removed, we have fully moved to composer.

Slim: registerAutoloader()已被刪除,我們已經完全遷移到composer。

Changes to container

$app->container->singleton(...) is now $container = $app->getContainer();
$container['...'] = function () {}; 

Please read Pimple docs for more info
複製程式碼

Removal of configureMode()

$app->configureMode(...) has been removed in v3.

Removal of PrettyExceptions

PrettyExceptions cause lots of issues for many people, so these have been removed. 漂亮的異常會給很多人帶來很多問題,所以這些已經被刪除了。

Route::setDefaultConditions(…) has been removed

We have switched routers which enable you to keep the default conditions regex inside of the route pattern. 我們已經切換路由器,使您能夠保留路由模式中的預設條件regex。

Changes to redirect

In Slim v2.x one would use the helper function $app->redirect(); to trigger a redirect request. In Slim v3.x one can do the same with using the Response class like so.

在Slim v2.x 使用助手函式$app->redirect();觸發重定向請求。在Slim v3.x 使用Response類也可以這樣做。

Example:

$app->get('/', function ($req, $res, $args) {
  return $res->withStatus(302)->withHeader('Location', 'your-new-uri');
});
Alternatively, if you want a route to redirect without any other handling, you can use the shortcut helper function $app->redirect() as the route definition:
$app->redirect('/', 'your-new-uri');
複製程式碼

Middleware Signature(中介軟體特性)

The middleware signature has changed from a class to a function.

中介軟體特性已從類更改為函式。

New signature:

use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

$app->add(function (Request $req,  Response $res, callable $next) {
    // Do stuff before passing along
    $newResponse = $next($req, $res);
    // Do stuff after route is rendered
    return $newResponse; // continue
});
複製程式碼

You can still use a class:

namespace My;

use Psr\Http\Message\RequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class Middleware
{
    function __invoke(Request $req,  Response $res, callable $next) {
        // Do stuff before passing along
        $newResponse = $next($req, $res);
        // Do stuff after route is rendered
        return $newResponse; // continue
    }
}


// Register
$app->add(new My\Middleware());
// or
$app->add(My\Middleware::class);
複製程式碼

Middleware Execution(執行中介軟體)

Application middleware is executed as Last In First Executed (LIFE).

應用程式中介軟體作為第一次執行(生命週期)中的最後一個執行

Flash Messages(Flash的訊息)

Flash messages are no longer a part of the Slim v3 core but instead have been moved to seperate Slim Flash package.

Flash訊息不再是Slim v3核心的一部分,而是被遷移成了獨立的Slim Flash包。

Cookies

In v3.0 cookies has been removed from core. See FIG Cookies for a PSR-7 compatible cookie component.

在v3.0中cookies已經從核心中移除。參見FIG Cookies瞭解PSR-7相容的cookie元件。

Removal of Crypto

In v3.0 we have removed the dependency for crypto in core.

在v3.0中,我們已經消除了Crypto的依賴。

New Router

Slim now utilizes FastRoute, a new, more powerful router!

This means that the specification of route patterns has changed with named parameters now in braces and square brackets used for optional segments:

Slim現在利用FastRoute,一個新的,更強大的路由器!

這意味著路由模式的規範已經發生了變化,命名引數現在在大括號和方括號中用於可選段:

// named parameter:
$app->get('/hello/{name}', /*...*/);

// optional segment:
$app->get('/news[/{year}]', /*...*/);
複製程式碼

Route Middleware

The syntax for adding route middleware has changed slightly. In v3.0:

新增路由中介軟體的語法略有變化。在v3.0:

$app->get(…)->add($mw2)->add($mw1);
複製程式碼

Getting the current route

The route is an attribute of the Request object in v3.0:

路由是v3.0中請求物件的一個屬性:

$request->getAttribute('route');
複製程式碼

When getting the current route in middleware, the value for determineRouteBeforeAppMiddleware must be set to true in the Application configuration, otherwise the getAttribute call returns null.

當在中介軟體中獲取當前路由時,應用程式配置中必須將defineroutebeforeappmiddleware的值設定為true,否則getAttribute呼叫將返回null。

urlFor() is now pathFor() in the router(urlFor()現在是路由器中的pathFor())

urlFor() has been renamed pathFor() and can be found in the router object:

urlFor()被重新命名為pathFor(),可以在router物件中找到:

$app->get('/', function ($request, $response, $args) {
    $url = $this->router->pathFor('home');
    $response->write("<a href='$url'>Home</a>");
    return $response;
})->setName('home');
複製程式碼

Also, pathFor() is base path aware.

此外,pathFor()是基本路徑感知的。

Container and DI … Constructing

Slim uses Pimple as a Dependency Injection Container.

Slim使用Pimple作為依賴注入容器。

// index.php
$app = new Slim\App(
    new \Slim\Container(
        include '../config/container.config.php'
    )
);

// Slim will grab the Home class from the container defined below and execute its index method.
// If the class is not defined in the container Slim will still contruct it and pass the container as the first arugment to the constructor!
$app->get('/', Home::class . ':index');


// In container.config.php
// We are using the SlimTwig here
return [
    'settings' => [
        'viewTemplatesDirectory' => '../templates',
    ],
    'twig' => [
        'title' => '',
        'description' => '',
        'author' => ''
    ],
    'view' => function ($c) {
        $view = new Twig(
            $c['settings']['viewTemplatesDirectory'],
            [
                'cache' => false // '../cache'
            ]
        );

        // Instantiate and add Slim specific extension
        $view->addExtension(
            new TwigExtension(
                $c['router'],
                $c['request']->getUri()
            )
        );

        foreach ($c['twig'] as $name => $value) {
            $view->getEnvironment()->addGlobal($name, $value);
        }

        return $view;
    },
    Home::class => function ($c) {
        return new Home($c['view']);
    }
];
複製程式碼

PSR-7 Objects

Request, Response, Uri & UploadFile are immutable. This means that when you change one of these objects, the old instance is not updated.

請求、響應、Uri和UploadFile是不可變的。 這意味著當您更改其中一個物件時,舊例項不會更新。

// This is WRONG. The change will not pass through.
$app->add(function (Request $request, Response $response, $next) {
    $request->withAttribute('abc', 'def');
    return $next($request, $response);
});

// This is correct.
$app->add(function (Request $request, Response $response, $next) {
    $request = $request->withAttribute('abc', 'def');
    return $next($request, $response);
});
複製程式碼

Message bodies are streams(訊息體是流)

// ...
$image = __DIR__ . '/huge_photo.jpg';
$body = new Stream($image);
$response = (new Response())
     ->withStatus(200, 'OK')
     ->withHeader('Content-Type', 'image/jpeg')
     ->withHeader('Content-Length', filesize($image))
     ->withBody($body);
// ...
複製程式碼

For text:

// ...
$response = (new Response())->getBody()->write('Hello world!')

// Or Slim specific: Not PSR-7 compliant.
$response = (new Response())->write('Hello world!');
// ...
複製程式碼

Web Servers(WEB伺服器)

It is typical to use the front-controller pattern to funnel appropriate HTTP requests received by your web server to a single PHP file. The instructions below explain how to tell your web server to send HTTP requests to your PHP front-controller file.

通常使用前端控制器模式將web伺服器接收到的適當HTTP請求引導到單個PHP檔案。下面的說明說明了如何告訴web伺服器將HTTP請求傳送到PHP前端控制器檔案。

PHP built-in server(PHP內建伺服器)

Run the following command in terminal to start localhost web server, assuming ./public/ is public-accessible directory with index.php file:

假設./public/是帶有index.php檔案的公共可訪問目錄,在終端中執行以下命令啟動localhost web伺服器:

php -S localhost:8888 -t public public/index.php
複製程式碼

If you are not using index.php as your entry point then change appropriately.

如果您沒有使用index.php作為入口點,那麼請進行適當的更改。

Apache configuration

Ensure your .htaccess and index.php files are in the same public-accessible directory. The .htaccess file should contain this code:

確保.htaccess和index.php檔案位於同一個公共訪問目錄中。.htaccess檔案應該包含以下程式碼:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
複製程式碼

This .htaccess file requires URL rewriting. Make sure to enable Apache’s mod_rewrite module and your virtual host is configured with the AllowOverride option so that the .htaccess rewrite rules can be used:

這個.htaccess檔案需要URL重寫。請確保啟用Apache的mod_rewrite模組,並且您的虛擬主機配置了AllowOverride選項,以便可以使用.htaccess重寫規則:

AllowOverride All
複製程式碼

Nginx configuration

This is an example Nginx virtual host configuration for the domain example.com. It listens for inbound HTTP connections on port 80. It assumes a PHP-FPM server is running on port 9000. You should update the server_name, error_log, access_log, and root directives with your own values. The root directive is the path to your application’s public document root directory; your Slim app’s index.php front-controller file should be in this directory.

這是一個為example.com配置的Nginx虛擬主機配置示例。它偵聽埠80上的入站HTTP連線。它假設PHP-FPM伺服器執行在埠9000上。您應該使用自己的值更新server_name、error_log、access_log和根指令。根指令是應用程式的公共文件根目錄的路徑;Slim應用程式的index.php前端控制器檔案應該在這個目錄中。

server {
    listen 80;
    server_name example.com;
    index index.php;
    error_log /path/to/example.error.log;
    access_log /path/to/example.access.log;
    root /path/to/public;

    location / {
        try_files $uri /index.php$is_args$args;
    }

    location ~ \.php {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_index index.php;
        fastcgi_pass 127.0.0.1:9000;
    }
}
複製程式碼

HipHop Virtual Machine

Your HipHop Virtual Machine configuration file should contain this code (along with other settings you may need). Be sure you change the SourceRoot setting to point to your Slim app’s document root directory.

您的HipHop虛擬機器配置檔案應該包含此程式碼(以及您可能需要的其他設定)。確保將SourceRoot設定更改為指向Slim應用程式的文件根目錄。

Server {
    SourceRoot = /path/to/public/directory
}

ServerVariables {
    SCRIPT_NAME = /index.php
}

VirtualHost {
    * {
        Pattern = .*
        RewriteRules {
                * {
                        pattern = ^(.*)$
                        to = index.php/$1
                        qsa = true
                }
        }
    }
}
複製程式碼

IIS

Ensure the Web.config and index.php files are in the same public-accessible directory. The Web.config file should contain this code:

確保Web.config和index.php檔案位於同一個公共訪問目錄中。Web.config應該包含以下程式碼:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="slim" patternSyntax="Wildcard">
                    <match url="*" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
複製程式碼

lighttpd

Your lighttpd configuration file should contain this code (along with other settings you may need). This code requires lighttpd >= 1.4.24.

您的lighttpd配置檔案應該包含此程式碼(以及您可能需要的其他設定)。這段程式碼需要lighttpd >= 1.4.24。

url.rewrite-if-not-file = ("(.*)" => "/index.php/$0")
複製程式碼

This assumes that Slim’s index.php is in the root folder of your project (www root).

這假設Slim的index.php位於專案的根資料夾(www root)中。

Deployment(部署)

Congratulations! if you have made it this far, that means you have successfully built something awesome using Slim. However, the time to party has not come yet. We still have to push our application to the production server.

There are many ways to do this that are beyond the scope of this documentation. In this section, we provide some notes for various set-ups.

恭喜你!如果你已經做到了這一步,那就意味著你已經成功地使用Slim建立了一些很棒的東西。然而,聚會慶祝的時間還沒有到。我們仍然必須將應用程式推到生產伺服器。

有許多本文件之外的方法同樣可以做到這一點。在本節中,我們將為各種設定提供一些註釋。

Disable error display in production

The first thing to do is to tweak your settings (src/settings.php in the skeleton application) and ensure that you do not display full error details to the public.

首先要做的是調整設定(骨架應用程式中的src/settings.php),並確保不會向公眾顯示完整的錯誤細節。

  'displayErrorDetails' => false, // set to false in production
複製程式碼

You should also ensure that your PHP installation is configured to not display errors with the php.ini setting:

display_errors = 0
複製程式碼

Deploying to your own server

If you control your server, then you should set up a deployment process using any one of the many deployment system such as:

如果你控制你的伺服器,你應該使用以下任何一個部署系統來建立部署過程:

  • Deploybot
  • Capistrano
  • Script controlled with Phing, Make, Ant, etc.

Deploying to a shared server

If your shared server runs Apache, then you need to create a .htaccess file in your web server root directory (usually named htdocs, public, public_html or www) with the following content:

如果共享伺服器執行Apache,則需要在web伺服器根目錄(通常名為htdocs、public、public_html或www)中建立一個.htaccess檔案,內容如下:

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule ^$ public/     [L]
   RewriteRule (.*) public/$1 [L]
</IfModule>
複製程式碼

(replace ‘public’ with the correct name of your domain name e.g. example.com/$1)

將“public”替換為您的域名的正確名稱,例如example.com/$1

Now upload all the files that make up your Slim project to the webserver. As you are on shared hosting, this is probably done via FTP and you can use any FTP client, such as Filezilla to do this.

現在將構成Slim專案的所有檔案上傳到web伺服器。由於您是在共享主機上,這可能是通過FTP完成的,您可以使用任何FTP客戶機,比如Filezilla來完成這一任務。

相關文章