Middleware

The middleware gives a single shot to the views associated into Controllers, before executing the requested Method, and store the resulted data in a Views shared storage, from where its loaded and added for rendering execution. This style avoids multiple calling of those Hooks, as in for every rendering call.

In the Core\View there is a Method, called "share", permitting to set data variables which are shared by any called rendering method. For example, it is possible to have:

return View::share('title', 'Page Title');

Making the variable 'title' available in any rendering command.

When a request is initiated a "before" method is automatically executed, it by default executes the Views associated Hooks and share their result to Core\View. This allows to fine tune the Controller behavior, for example hosting logic to check the user authentication or do whatever pre-processing, i.e. checking access codes, without requiring to add commands to every method, simplifying the code.

A complex example of its chained usage can be:

// Into a Base Controller

protected function before()
{
// Check if the User is authorized to use the requested Method.
switch ($this->getMethod()) {
case 'login':
case 'forgot':
case 'reset':
break;
default:
if (Session::get('loggedIn') == false) {
Url::redirect('login');
}
}; // Leave to parent's Method the execution decisions.
return parent::before(); // <-- there are loaded the Views associated Hooks.
}
// Into an Admin Controller protected function before()
{
// Check the CSRF token for select Methods over POST, e.g: add/edit/delete.
switch($this->getMethod()) {
case 'index':
case 'show':
break;
default:
if (Request::isPost() && ! Csrf::isTokenValid()) {
Url::redirect('login');
}
}; // Leave to parent's Method the execution decisions.
return parent::before(); // <-- there is checked the User Authorization.
}

Another more complex example, for a Controller for private files serving; with access authorization and limit the access time:

protected function before()
{
// Only the authorized Users can arrive to the Methods from this Controller.
if (Session::get('loggedIn') == false) {
Url::redirect('login');
} //
if($this->getMethod() == 'files') {
$params = $this->params(); if(count($params) != 3) {
header("HTTP/1.0 400 Bad Request"); return false;
} // The current timestamp.
$timestamp = time(); // File access validation elements.
$validation = $params[0];
$time = $params[1];
$filename = $params[2]; $clientip = $this->getIpAddress(); $hash = hash('sha256', $clientip.$filename.$time.FILES_ACCESSKEY); if((($timestamp - $time) > FILES_VALIDITY) || ($validation != $hash)) {
header("HTTP/1.0 403 Forbidden"); return false;
}
} else if (Request::isPost()) {
// All the POST requests should have a CSRF Token there.
if (! Csrf::isTokenValid()) {
Url::redirect('login');
}
} // Leave to parent's Method the execution decisions.
return parent::before(); // <-- there are loaded the Views associated Hooks.
}

Also, the part of Method flow execution was moved into Core\Controller::execute(), presenting the big advantage to simplify the Routing and permitting to have the before/after methods protected, safe against their execution from outside.

Finally, into Core\Controller was introduced an new method called "trans", wrapping up the Language translation. Then, permitting commands like:

// Actual style
$data['title'] = $this->language->get('welcomeText');
$data['welcomeMessage'] = $this->language->get('welcomeMessage'); // New style
$data['title'] = $this->trans('welcomeText');
$data['welcomeMessage'] = $this->trans('welcomeMessage');

Example of using "View::share()"

public function index()
{
$title = $this->trans('welcomeText'); $data['welcomeMessage'] = $this->trans('welcomeMessage'); // Make $title available in all Views rendering
View::share('title', $title); View::renderTemplate('header'); // <-- No need for $data in this case
View::render('Welcome/Welcome', $data);
View::renderTemplate('footer'); // <-- No need for $data in this case
}

What is difference between applying pre-processing in "__constructor()" and "before()" ?

Comparative with running checks in Class Constructor, the before() method is executed WHEN the requested Method is a valid one, both as in existing and being "callable", and it have at its disposition the requested Method name and the associated Parameters; both passed to by Routing. Then, before() can accurate tune the Controller behavior, depending on requested Method.

Is required to implement the methods "before()" and "after()" in every Controller ?

No. You can safely completely ignore their existence if you don't want to fine tune the Controller's behavior via that Middleware.

What if I want a base Controller which do NOT call the Views associated Hooks ?

Just override the before() like below in a Base Controller, e.g. App\Core\Controller

namespace App\Core;

use Core\Controller as BaseController

class Controller extends BaseController
{
public function __construct()
{
parent::__construct();
} protected function before()
{
return true;
}
}

Then use this Class as a base for your Controllers.

Middleware的更多相关文章

  1. 用Middleware给ASP.NET Core Web API添加自己的授权验证

    Web API,是一个能让前后端分离.解放前后端生产力的好东西.不过大部分公司应该都没能做到完全的前后端分离.API的实现方式有很 多,可以用ASP.NET Core.也可以用ASP.NET Web ...

  2. [转]Writing Custom Middleware in ASP.NET Core 1.0

    本文转自:https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/ One of the new ...

  3. [转]用Middleware给ASP.NET Core Web API添加自己的授权验证

    本文转自:http://www.cnblogs.com/catcher1994/p/6021046.html Web API,是一个能让前后端分离.解放前后端生产力的好东西.不过大部分公司应该都没能做 ...

  4. [译]Writing Custom Middleware in ASP.NET Core 1.0

    原文: https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/ Middleware是ASP. ...

  5. 解读ASP.NET 5 & MVC6系列(6):Middleware详解

    在第1章项目结构分析中,我们提到Startup.cs作为整个程序的入口点,等同于传统的Global.asax文件,即:用于初始化系统级的信息(例如,MVC中的路由配置).本章我们就来一一分析,在这里如 ...

  6. 在ASP.NET Core使用Middleware模拟Custom Error Page功能

    一.使用场景 在传统的ASP.NET MVC中,我们可以使用HandleErrorAttribute特性来具体指定如何处理Action抛出的异常.只要某个Action设置了HandleErrorAtt ...

  7. ASP.NET Core 开发-中间件(Middleware)

    ASP.NET Core开发,开发并使用中间件(Middleware). 中间件是被组装成一个应用程序管道来处理请求和响应的软件组件. 每个组件选择是否传递给管道中的下一个组件的请求,并能之前和下一组 ...

  8. ASP.NET Core中间件(Middleware)实现WCF SOAP服务端解析

    ASP.NET Core中间件(Middleware)进阶学习实现SOAP 解析. 本篇将介绍实现ASP.NET Core SOAP服务端解析,而不是ASP.NET Core整个WCF host. 因 ...

  9. [ASP.NET Core] Static File Middleware

    前言 本篇文章介绍ASP.NET Core里,用来处理静态档案的Middleware,为自己留个纪录也希望能帮助到有需要的开发人员. ASP.NET Core官网 结构 一个Web站台最基本的功能,就 ...

  10. [ASP.NET Core] Middleware

    前言 本篇文章介绍ASP.NET Core里,用来处理HTTP封包的Middleware,为自己留个纪录也希望能帮助到有需要的开发人员. ASP.NET Core官网 结构 在ASP.NET Core ...

随机推荐

  1. C++学习笔记:Vector容器

    vector v:初始化一个0大小的向量 vector v(10):初始化一个10个大小的向量 push_back:增加一个元素 pop:删除一个元素,不返回 front:返回第一个元素 back:返 ...

  2. Sharepoint网站创建自定义导航全记录

    转:http://tech.it168.com/a2009/1207/820/000000820524_all.shtml [IT168 技术文档]在一个Sharepoint网站中可以创建子网站,页面 ...

  3. Android学习系列(22)--App主界面比较

    本文算是一篇漫谈,谈一谈当前几个流行应用的主界面布局,找个经典的布局我们自己也来实现一个.不是为了追求到底有多难,而是为了明白我们确实需要这么做. 走个题,android的UI差异化市场依然很大,依然 ...

  4. Rails常用命令

    rails new Project rails g scaffold location uuid:string deviceid:string latitude:float longitude:flo ...

  5. HDU 1495 非常可乐 BFS搜索

    题意:有个为三个杯子(杯子没有刻度),体积为s,n,m,s=m+n, 刚开始只有体积为s的杯子装满可乐,可以互相倒,问你最少的次数使可乐均分,如果没有结果,输出-1; 分析:直接互相倒就完了,BFS模 ...

  6. PHP 判断协议是否为HTTPS

    if ($_SERVER['HTTPS'] != "on") { echo "This is not HTTPS"; }else{ echo "Thi ...

  7. 在App里面添加App Store中App链接的解决方法

    详见stackoverflow.com/questions/433907/how-to-link-to-apps-on-the-app-store http://developer.apple.com ...

  8. SMG12232A2标准图形点阵型液晶显示模块的演示程序[C51编程语言]

    //SMG12232A2标准图形点阵型液晶显示模块的演示程序[C51编程语言][MCS51总线接口方式] //应用产品: SMG12232A2标准图形点阵型液晶显示模块 // 本演示程序适用于SMG1 ...

  9. 题解西电OJ (Problem 1004 -亚特兰提斯)--最小生成树

    Description 为了找寻沉睡的亚特兰提斯大陆,wm来到了大西洋上进行探险,找了半个月仍一无所获.然而在一次突袭而来的暴风雨后,wm的船莫名地驶入了一片未知的区域,发现了一个地图上未标记的岛屿, ...

  10. 【恒天云】OpenStack和CloudStack对比研究报告

    摘自恒天云:http://www.hengtianyun.com/download-show-id-8.html 1. 概述 常见的IaaS开源平台有OpenStack.CloudStack.Euca ...