网络科技

    今日:1005| 主题:246504
收藏本版
互联网、科技极客的综合动态。

[其他] Getting Started with SLIM 3, A PHP Microframework

[复制链接]
不念不忘少年蓝 发表于 2016-11-29 03:53:48
110 2

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
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.
  But there are some libraries that separate themselves from the chaff, one such example is the    Laravel PHP framework.  
  Another framework that sets itself apart is    SLIM.  
  What is SLIM?

  Taking it straight from the horse's mouth,
  Slim is a PHP    microframework that helps you quickly write simple yet powerful web applications and    APIs.  
  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    Open-closed principle.  
  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.
  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.
  Features of SLIM

  When it comes to using SLIM, there are four main features:
  
       
  •       HTTP Router: this allows developers to map functions/callbacks to HTTP methods and URLs.   
  •       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 coversLaravel middlewares. Sure the implementations might be a tad different, but they offer the same functionality.   
  •               Dependency Injection      : 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      PHP-FIG.  
  Installing SLIM

  To get SLIM installed on your computer, the fastest way is to usecomposer to install askeletal version of SLIM. But for this tutorial, we will only install    SLIM coreand then walk through configuring SLIM for a simple application request-response cycle.  
  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.
  1. composer require slim/slim "^3.0"
复制代码
NOTE:at the time of writing this article, the current version of SLIM is version    3.5.0.  
  Basic routing

  Ah, the obligatory "Hello World" application. This example will illustrate how easy it is to use SLIM.
  In our project directory, we should only see our composer files and a vendor directory. We can then create a    index.phpfile.  
  In that file, we add this little code snippet.
  1. <?php
  2. require __DIR__ . '/vendor/autoload.php';
  3. $app = new Slim\App;
  4. $app->get('/', function ($request, $response) {
  5.     return 'hello world';
  6. });
  7. $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.  
  To see our message in the browser, in the root of our working directory, we boot a PHP server.
  1. php -S localhost:8000
复制代码
If you open    localhost:8000in the browser, you should see "hello world". If you use a different server, you should check out the section on.  
  Other HTTP methods

  The above example only simulated a    GETrequest, 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.  
  1. <?php
  2. $app->post('/', function ($request, $response) {
  3.     return 'hello world';
  4. });
复制代码
The above route now will only work for POST requests. We can call the rest of the HTTP methods the same way.
  The route discussion in this article is a bit vague, in an upcoming article, we will talk about routing in SLIM.
  Render views with Twig

  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.
  There are a lot of templates engines for PHP, but for this tutorial, we will stick with    Twig.  
  Twig allows us to use custom properties to write PHP template files. It compiles to pure PHP code.
  To display a variable in twig, we do this.
  1. {{ var }}
复制代码
This then compiles itself to:
  1. <?php echo $var ?>
复制代码
We could create global template layouts that we can later extend and keep our page layout and styling consistent.
  1. {% extends "layout.html" %}
  2. {% block content %}
  3.     The content of the page...
  4. {% 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    Smarty.  
  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.
  1. composer require slim/twig-view
复制代码
Now that we have twig installed, let's create a    templatesdirectory in the root of our project. We can now register twig as our view engine/manager in SLIM. In our    index.phpfile, we add this snippet before our routes.  
  1. <?php
  2. // ...
  3. $container = $app->getContainer();
  4. $container['view'] = function ($container) {
  5.     $templates = __DIR__ . '/templates/';
  6.     $cache = __DIR__ . '/tmp/views/';
  7.     $view = new Slim\Views\Twig($templates, compact('cache'));
  8.     return $view;
  9. };
复制代码
First, we grab our app    $containerand 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    $containerinstance.  
  Then we create an instance of    Slim\Views\Twigand pass in the directory of our templates, and the second parameter is an array (    compactconverts variables to array key-value pairs) where we can pass the location to our template cache directory.  
  We can disable caching by setting the    $cachevariable to    false. After that, we can return the    $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.
  1. $app->get('/', function ($request, $response) {
  2.     return $this->view->render($response, 'home.twig');
  3. });
复制代码
Note:make sure you have a file name    home.twigin your templates directory. Whatever you place in that file gets rendered in the browser.  
  Server Configuration

  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    web serverssection on SLIM's website.  
  Apache

  Wherever you decide to make the root of your application, create a new    .htaccessfile and place the following snippet in that file.  
  1. <?php
  2. require __DIR__ . '/vendor/autoload.php';
  3. $app = new Slim\App;
  4. $app->get('/', function ($request, $response) {
  5.     return 'hello world';
  6. });
  7. $app->run();0
复制代码
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.phpfile.  
  Nginx

  1. <?php
  2. require __DIR__ . '/vendor/autoload.php';
  3. $app = new Slim\App;
  4. $app->get('/', function ($request, $response) {
  5.     return 'hello world';
  6. });
  7. $app->run();1
复制代码
This configuration is similar to the apache's configuration, don't forget to replace    example.com.  
  Conclusion

  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). Simple is an excellent framework, it is easy to use, lightweight, extensible etc. What's not to love.
友荐云推荐




上一篇:Testing Services with Http in Angular 2
下一篇:Instagram will notify users if you take a screenshot from their stories
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

amy3299 发表于 2016-11-30 08:46:47
路过 帮顶 嘿嘿
回复 支持 反对

使用道具 举报

mswip 发表于 2016-11-30 09:06:13
有钱的捧个钱场,没钱的回家拿钱捧个钱场。
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表