博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
slim3框架 教程_SLIM 3入门,PHP微框架
阅读量:2524 次
发布时间:2019-05-11

本文共 10312 字,大约阅读时间需要 34 分钟。

slim3框架 教程

Just like the world of Javascript, in the world of PHP, we have a fairly large amount of frameworks and libraries. We could go on all day listing PHP libraries and still not finish in time for Christmas.

就像Java语言世界和PHP世界一样,我们拥有大量的框架和库。 我们可以整日列出PHP库,但仍无法及时完成圣诞节。

But there are some libraries that separate themselves from the chaff, one such example is the .

但是有些库将自己与谷壳分开,其中一个例子是 。

Another framework that sets itself apart is .

另一个与众不同的框架是 。

( )

Taking it straight from the horse's mouth,

从马口直接拿出来

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.

Slim是一个PHP 框架,可帮助您快速编写简单但功能强大的Web应用程序和API

Emphasis on "micro" and "APIs". SLIM is not robust with lots of features, what makes it so good is the fact that it creates room for extensibility, thus kinda obeying the .

强调“微型”和“ API”。 SLIM具有许多功能并不强大,因此使它如此出色的原因是它为可扩展性创造了空间,因此有点遵循 。

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的核心是一个调度程序,它接收HTTP请求,调用适当的回调例程并返回HTTP响应。 而已。

The fact that SLIM doesn't come with many dependencies makes it one of the best frameworks out there when it comes to API development.

SLIM没有很多依赖关系这一事实使它成为API开发中最好的框架之一。

( )

When it comes to using SLIM, there are four main features:

在使用SLIM时,有四个主要功能:

  • HTTP Router: this allows developers to map functions/callbacks to HTTP methods and URLs.

    HTTP路由器 :这使开发人员可以将函数/回调映射到HTTP方法和URL。
  • Middlewares: serve as layers to allow developers modify HTTP requests and response. If you need further explanation on middlewares, there is an article here on Scotch that covers . Sure the implementations might be a tad different, but they offer the same functionality.

    中间件 :用作允许开发人员修改HTTP请求和响应的层。 如果您需要有关中间件的进一步说明,请 Scotch上的一篇文章,其中涉及 。 当然,这些实现可能有所不同,但是它们提供了相同的功能。
  • : makes it possible for developers to have complete control over managing dependencies within applications.

    :使开发人员可以完全控制应用程序中的依赖关系管理。
  • PSR-7 support: this is not really a feature, more like a standard. It defines the way HTTP requests and responses should be handled in web applications. You can read more about it on .

    PSR-7支持 :这并不是真正的功能,更像是一个标准。 它定义了在Web应用程序中处理HTTP请求和响应的方式。 您可以在上阅读有关它的更多信息。

( )

To get SLIM installed on your computer, the fastest way is to use to install a of SLIM. But for this tutorial, we will only install and then walk through configuring SLIM for a simple application request-response cycle.

要在计算机上安装SLIM,最快的方法是使用安装SLIM的 。 但是对于本教程,我们将仅安装 ,然后逐步完成配置SLIM的过程,以实现简单的应用程序请求-响应周期。

To install SLIM we use composer, we create our working directory (call it whatever you want). Then, we move into that directory and run the following composer command which should install SLIM on our machine.

要使用composer安装SLIM,请创建我们的工作目录(随心所欲地调用它)。 然后,我们进入该目录并运行以下composer命令,该命令应在我们的计算机上安装SLIM。

composer require slim/slim"^3.0"

NOTE: at the time of writing this article, the current version of SLIM is version 3.5.0.

注意:在撰写本文时,SLIM的当前版本是3.5.0版。

( )

Ah, the obligatory "Hello World" application. This example will illustrate how easy it is to use SLIM.

啊,必须的“ Hello World”应用程序。 此示例将说明使用SLIM非常容易。

In our project directory, we should only see our composer files and a vendor directory. We can then create a index.php file.

在我们的项目目录中,我们应该只看到我们的作曲家文件和一个供应商目录。 然后,我们可以创建一个index.php文件。

In that file, we add this little code snippet.

在该文件中,我们添加了这个小代码段。

get('/', function ($request, $response) {
return 'hello world';});$app->run();

First, we load composer's autoloader, then we create a new instance of the Slim\App, then call a get method to the home path, and pass a closure that takes in the request and response, and then return "hello world" (which is converted to a response object by SLIM. Outside the closure, we run the app.

首先,我们加载作曲家的自动加载器,然后创建Slim\App的新实例,然后向本地路径调用get方法,并传递一个接受请求和响应的闭包,然后返回“ hello world” (由SLIM转换为响应对象。在闭包之外,我们运行该应用。

To see our message in the browser, in the root of our working directory, we boot a PHP server.

要在浏览器中查看我们的消息,请在工作目录的根目录中启动PHP服务器。

php -S localhost:8000

If you open in the browser, you should see "hello world". If you use a different server, you should check out the section on .

如果在浏览器中打开 ,则应该看到“ hello world”。 如果您使用其他服务器,则应查看有关的部分。

其他HTTP方法 (Other HTTP methods)

The above example only simulated a GET request, as we all know, there are more request types like POST, PUT, PATCH, DELETE, OPTIONS. To use any of these methods in SLIM, we literarily do the same thing we did with the get method above.

上面的示例仅模拟了GET请求,众所周知,还有更多的请求类型,如POSTPUTPATCHDELETEOPTIONS 。 要在SLIM中使用这些方法中的任何一种,我们实际上在做与上述get方法相同的事情。

post('/', function ($request, $response) {
return 'hello world';});

The above route now will only work for POST requests. We can call the rest of the HTTP methods the same way.

上面的路由现在仅适用于POST请求。 我们可以用相同的方式调用其余的HTTP方法。

The route discussion in this article is a bit vague, in an upcoming article, we will talk about routing in SLIM.

本文中的路由讨论有点含糊,在下一篇文章中,我们将讨论SLIM中的路由。

( )

Say we are building an application that is not an API with SLIM, we need a way to organize our templates, not that SLIM requires any template of sorts, but templates make it easier to manage our view files.

假设我们正在使用SLIM构建不是API的应用程序,我们需要一种组织模板的方法,不是SLIM需要任何种类的模板,而是通过模板可以更轻松地管理视图文件。

There are a lot of templates engines for PHP, but for this tutorial, we will stick with .

有很多用于PHP的模板引擎,但是在本教程中,我们将坚持使用 。

Twig allows us to use custom properties to write PHP template files. It compiles to pure PHP code.

Twig允许我们使用自定义属性来编写PHP模板文件。 它编译为纯PHP代码。

To display a variable in twig, we do this.

要在树枝中显示变量,我们可以这样做。

{
{
var }}

This then compiles itself to:

然后将其编译为:

We could create global template layouts that we can later extend and keep our page layout and styling consistent.

我们可以创建全局模板布局,以便以后扩展并保持页面布局和样式一致。

{
% extends "layout.html" %}{
% block content %} The content of the page...{
% endblock %}

Twig offers many more features. It is also one of the most stable and best PHP template languages out there. Another alternative to twig is Blade (for Laravel), or .

Twig提供了更多功能。 它也是目前最稳定,最好PHP模板语言之一。 树枝的另一种替代方法是Blade(适用于Laravel)或 。

安装树枝 (Installing Twig)

To get started, we need to install Twig and to do that, we go into the root of our application and run the following command.

首先,我们需要安装Twig,然后进入应用程序的根目录并运行以下命令。

composer require slim/twig-view

Now that we have twig installed, let's create a templates directory in the root of our project. We can now register twig as our view engine/manager in SLIM. In our index.php file, we add this snippet before our routes.

现在已经安装了树枝,让我们在项目的根目录中创建一个模板目录。 现在,我们可以将细枝注册为SLIM中的视图引擎/管理器。 在我们的index.php文件中,我们在路由之前添加此代码段。

getContainer();$container['view'] = function ($container) {
$templates = __DIR__ . '/templates/'; $cache = __DIR__ . '/tmp/views/'; $view = new Slim\Views\Twig($templates, compact('cache')); return $view;};

First, we grab our app $container and add a new property called view. We name it whatever we want (template, page etc). Just note that this value is important as we will need to reference it soon. We pass a closure which takes in the $container instance.

首先,我们获取应用程序$container并添加一个名为view的新属性。 我们根据需要命名(模板,页面等)。 请注意,此值很重要,因为我们需要尽快引用它。 我们通过一个接受$container实例的闭包。

Then we create an instance of Slim\Views\Twig and pass in the directory of our templates, and the second parameter is an array (compact converts variables to array key-value pairs) where we can pass the location to our template cache directory.

然后,我们创建一个Slim\Views\Twig实例,并传入模板目录,第二个参数是一个数组( compact将变量转换为数组键值对),在这里我们可以将该位置传递给模板缓存目录。

We can disable caching by setting the $cache variable to false. After that, we can return the $view.

我们可以通过将$cache变量设置为false来禁用缓存。 之后,我们可以返回$view

To actually use our view files in our routes, we can go back into our router and then return a view file like this.

要在路线中实际使用我们的视图文件,我们可以返回到路由器,然后返回这样的视图文件。

$app->get('/', function ($request, $response) {
return $this->view->render($response, 'home.twig');});

Note: make sure you have a file name home.twig in your templates directory. Whatever you place in that file gets rendered in the browser.

注意:确保模板目录中的文件名为home.twig 。 您在该文件中放置的任何内容都会在浏览器中呈现。

( )

There is a 100% chance that you don't use the PHP default server to serve your app in production. Odds are you choose between Apache and the lovely Nginx. For these servers, our routes won't work without a little URL rewriting. We see how to configure Apache and Nginx, if you use another server, you can check out the section on SLIM's website.

您有100%的机会不使用PHP默认服务器在生产环境中提供服务。 您很可能在Apache和可爱的Nginx之间进行选择。 对于这些服务器,如果不进行一些URL重写,我们的路由将无法工作。 我们看到了如何配置Apache和Nginx,如果您使用其他服务器,则可以在SLIM网站上查看“ 部分。

阿帕奇 (Apache)

Wherever you decide to make the root of your application, create a new .htaccess file and place the following snippet in that file.

无论您决定作为应用程序的根目录,都创建一个新的.htaccess文件,并将以下代码片段放入该文件中。

RewriteEngine OnRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^ index.php [QSA,L]

What this does is just serve files and directory that exists on the server, and if they don't exist then let the routing be handled by our index.php file.

这样做只是提供服务器上存在的文件和目录,如果不存在,则由我们的index.php文件处理路由。

Nginx的 (Nginx)

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 $document_root$fastcgi_script_name;        fastcgi_param SCRIPT_NAME $fastcgi_script_name;        fastcgi_index index.php;        fastcgi_pass 127.0.0.1:9000;    }}

This configuration is similar to the apache's configuration, don't forget to replace example.com.

此配置类似于apache的配置,请不要忘记替换example.com

( )

Frameworks like Laravel, Zend, Symfony etc are really good, but they are not necessary when it comes to building APIs and simple websites (they are too bloated). Slim is an excellent framework, it is easy to use, lightweight, extensible etc. What's not to love.

诸如Laravel,Zend,Symfony之类的框架确实不错,但是在构建API和简单网站(它们过于肿)时并不需要它们。 Slim是一个出色的框架,它易于使用,轻巧,可扩展等。

翻译自:

slim3框架 教程

转载地址:http://gwywd.baihongyu.com/

你可能感兴趣的文章
[效率提升]如何管理好你的电脑文件
查看>>
C++实验二
查看>>
使用case语句给字体改变颜色
查看>>
JAVA基础-多线程
查看>>
面试题5:字符串替换空格
查看>>
JSP九大内置对象及四个作用域
查看>>
ConnectionString 属性尚未初始化
查看>>
数据结构-栈 C和C++的实现
查看>>
MySQL基本命令和常用数据库对象
查看>>
poj 1222 EXTENDED LIGHTS OUT(位运算+枚举)
查看>>
进程和线程概念及原理
查看>>
Lucene、ES好文章
查看>>
android 生命周期
查看>>
jquery--this
查看>>
MySQL 5.1参考手册
查看>>
TensorFlow安装流程(GPU加速)
查看>>
OpenStack的容器服务体验
查看>>
【BZOJ 4059】 (分治暴力|扫描线+线段树)
查看>>
BZOJ 1066 蜥蜴(网络流)
查看>>
提高批量插入数据的方法
查看>>