教科書般的PHP框架學習指南php
注:翻譯水平有限,若有錯誤,歡迎指正html
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響應。就是這樣。web
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!api
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.bash
你並不老是須要像Symfony或Laravel那麼激進的解決方案。毫無疑問,這些都是很棒的工具。但它們每每是矯枉過正。相反,Slim只提供了一組最小的工具,它們只作您須要的事情,而不作其餘任何事情。服務器
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.cookie
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:app
首先,您須要像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();
複製代碼
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響應對象。
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上的第三方組件也很容易。
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的概念和體系結構,而後討論請求和響應處理、路由和錯誤處理等特定主題。
Web server with URL rewriting
PHP 5.5 or newer
複製代碼
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';
複製代碼
New PHP version
Slim 3 requires PHP 5.5+
複製代碼
Slim 3 uses \Slim\App for the Application object usually named $app.
$app = new \Slim\App();
複製代碼
$app->get('/', function (Request $req, Response $res, $args = []) {
return $res->withStatus(400)->write('Bad Request');
});
複製代碼
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(應用程序對象)實例的屬性。
$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 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。
In Slim v3 we have removed the HTTP-Caching into its own module Slim\Http\Cache.
在Slim v3中,咱們已經將Http緩存遷移到它本身的模塊Slim\Http\Cache中。
Slim Core has removed Stop/Halt. In your applications, you should transition to using the withStatus() and withBody() methods.
Slim內核已刪除Stop/Halt。在應用程序中,應該過渡到使用withStatus()和withBody()方法。
爲何有些框架愈來愈複雜,由於裏面充斥着過期的代碼,混淆了開發者,及時清理很重要,保持簡單,避免出現重複的輪子
Slim::registerAutoloader() have been removed, we have fully moved to composer.
Slim: registerAutoloader()已被刪除,咱們已經徹底遷移到composer。
$app->container->singleton(...) is now $container = $app->getContainer();
$container['...'] = function () {};
Please read Pimple docs for more info
複製代碼
$app->configureMode(...) has been removed in v3.
PrettyExceptions cause lots of issues for many people, so these have been removed. 漂亮的異常會給不少人帶來不少問題,因此這些已經被刪除了。
We have switched routers which enable you to keep the default conditions regex inside of the route pattern.
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');
複製代碼
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);
複製代碼
Application middleware is executed as Last In First Executed (LIFE).
應用程序首次被執行時,中間件被放在了最後執行
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包。
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組件。
In v3.0 we have removed the dependency for crypto in core.
在v3.0中,咱們已經消除了Crypto的依賴。
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}]', /*...*/);
複製代碼
The syntax for adding route middleware has changed slightly. In v3.0:
添加路由中間件的語法略有變化。在v3.0:
$app->get(…)->add($mw2)->add($mw1);
複製代碼
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() 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()是基本路徑感知的。
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']);
}
];
複製代碼
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);
});
複製代碼
// ...
$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!');
// ...
複製代碼
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前端控制器文件。
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做爲入口點,那麼請進行適當的更改。
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
複製代碼
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;
}
}
複製代碼
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
}
}
}
}
複製代碼
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>
複製代碼
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)中。
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建立了一些很棒的東西。然而,聚會慶祝的時間尚未到。咱們仍然必須將應用程序推到生產服務器。
有許多本文檔以外的方法一樣能夠作到這一點。在本節中,咱們將爲各類設置提供一些註釋。
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
複製代碼
If you control your server, then you should set up a deployment process using any one of the many deployment system such as:
若是你控制你的伺服器,你應該使用如下任何一個部署系統來創建部署過程:
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來完成這一任務。