代码研磨 Slim v3 (一)--app->get()&route->add()
index.php代码如下:
$app->get('/forbase', function ($request, $response, $args){
Example\Module\Base::instance()->init($request,$response);
return $response;
})->add(Example\MiddleWare\MyMiddleware::instance(Example\Module\Base::instance()));
APP->get()代码如下:
/**
* Add GET route
*
* @param string $pattern The route URI pattern
* @param mixed $callable The route callback routine
*
* @return \Slim\Interfaces\RouteInterface
*/
public function get($pattern, $callable)
{
return $this->map(['GET'], $pattern, $callable);
}
APP->map()代码如下:
/**
* Add route with multiple methods
*
* @param string[] $methods Numeric array of HTTP method names
* @param string $pattern The route URI pattern
* @param mixed $callable The route callback routine
*
* @return RouteInterface
*/
public function map(array $methods, $pattern, $callable)
{
if ($callable instanceof Closure) {
$callable = $callable->bindTo($this->container);
} $route = $this->container->get('router')->map($methods, $pattern, $callable);
if (is_callable([$route, 'setContainer'])) {
$route->setContainer($this->container);
} if (is_callable([$route, 'setOutputBuffering'])) {
$route->setOutputBuffering($this->container->get('settings')['outputBuffering']);
}
return $route;
}
执行完这个map方法后,这个route就被创建了。
$callable = $callable->bindTo($this->container);
用来将$this->container绑定到$callable中,这样$callable就可以访问container里的数据,but我没找到怎么用。这是遗留问题之一。
$route = $this->container->get('router')->map($methods, $pattern, $callable);
做了两件事:
1.获取router;
2.router调用map().
看看Slim\Container类:
class Container extends PimpleContainer implements ContainerInterface
{
/**
* Finds an entry of the container by its identifier and returns it.
*
* @param string $id Identifier of the entry to look for.
*
* @throws ContainerValueNotFoundException No entry was found for this identifier.
* @throws ContainerException Error while retrieving the entry.
*
* @return mixed Entry.
*/
public function get($id)
{
if (!$this->offsetExists($id)) {
throw new ContainerValueNotFoundException(sprintf('Identifier "%s" is not defined.', $id));
}
return $this->offsetGet($id);
}
}
get()会调用$this->offsetGet(),这个方法在Pimple\Container里。
看看PimpleContainer类:
class Container implements \ArrayAccess
{
public function offsetGet($id)
{
if (!isset($this->keys[$id])) {
throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
} if (
isset($this->raw[$id])
|| !is_object($this->values[$id])
|| isset($this->protected[$this->values[$id]])
|| !method_exists($this->values[$id], '__invoke')
) {
return $this->values[$id];
} if (isset($this->factories[$this->values[$id]])) {
return $this->values[$id]($this);
} $raw = $this->values[$id];
$val = $this->values[$id] = $raw($this);
$this->raw[$id] = $raw; $this->frozen[$id] = true; return $val;
}
}
这个类实现了\ArrayAccess接口,官方的解释是说呢,使得访问对象像访问对象那样,即obj['name']拿到name属性。其实能够像访问数组那样访问对象的原因在于ArrayAccess这个接口里的所有方法,在obj['name']就是访问了obj的offsetGet()方法。可以自己覆写这个方法,实现数据存入哪里已经从哪里取出。
这两句话也比较有意思:$raw = $this->values[$id];$val = $this->values[$id] = $raw($this); 一开始没搞懂$raw($this)是干什么的,因为经过上一步的$this->values[$id]其实就已经拿到Closure了,应该很应当的想到是Closure的参数。没有搞明白的原因在于我认为这一步就已经执行Closure了。我错了,$raw($this)这里才执行了闭包函数。是不是可以总结为只有Closure被调用了才执行,而调用应该来自 “=“的右侧。
map()用来创建新的route并添加到router中。
public function map($methods, $pattern, $handler)
{
if (!is_string($pattern)) {
throw new InvalidArgumentException('Route pattern must be a string');
} // Prepend parent group pattern(s)
if ($this->routeGroups) {
$pattern = $this->processGroups() . $pattern;
} // According to RFC methods are defined in uppercase (See RFC 7231)
$methods = array_map("strtoupper", $methods); // Add route
$route = new Route($methods, $pattern, $handler, $this->routeGroups, $this->routeCounter);
$this->routes[$route->getIdentifier()] = $route;
$this->routeCounter++; return $route;
}
$methods = array_map("strtoupper", $methods); 调用了库函数array_map,用途就是将$methods作为参数出传入'strtoupper'中。
new Route($methods, $pattern, $handler, $this->routeGroups, $this->routeCounter); 创建了新的route。
/**
* Route
*/
class Route extends Routable implements RouteInterface
{
public function __construct($methods, $pattern, $callable, $groups = [], $identifier = 0)
{
$this->methods = $methods;
$this->pattern = $pattern;
$this->callable = $callable;
$this->groups = $groups;
$this->identifier = 'route' . $identifier;
}
}
router中还给route标识了identify,其实就是'routeXX'的样式。
$route->setContainer($this->container);
$route->setOutputBuffering($this->container->get('settings')['outputBuffering']);为新添加的route设置container和outputBuffering。
最后,app->get()会返回一个route。
route add Middleware代码即index.php 中->add();
route->add()方法其实是使用Routable这个抽象类的。
/**
* A routable, middleware-aware object
*
* @package Slim
* @since 3.0.0
*/
abstract class Routable
{
/**
* Prepend middleware to the middleware collection
*
* @param mixed $callable The callback routine
*
* @return static
*/
public function add($callable)
{
$callable = $this->resolveCallable($callable);
if ($callable instanceof Closure) {
$callable = $callable->bindTo($this->container);
} $this->middleware[] = $callable;
return $this;
}
}
在add里还是做了一个绑定,让闭包函数可以访问$this->container。接着将Closure装入到middleware[]数组中,在这个closure也就是route middleware run的时候就会将middleware数组中的元素加入到Middleware stack中。通过CallMiddlewareStack来依次执行Middleware。
至此,APP成功添加了一个route,并且给这个route添加了一个middleware。
代码研磨 Slim v3 (一)--app->get()&route->add()的更多相关文章
- 代码研磨 Slim v3 (二)--app->run()
APP->run()代码如下: /** * Run application * * This method traverses the application middleware stac ...
- 开源电影项目源码案例重磅分析,一套代码发布小程序、APP平台多个平台
uni-app-Video GitHub地址:https://github.com/Tzlibai/uni-app-video 一个优秀的uni-app案例,旨在帮助大家更快的上手uni-app,共同 ...
- 【转】【翻】Android Design Support Library 的 代码实验——几行代码,让你的 APP 变得花俏
转自:http://mrfufufu.github.io/android/2015/07/01/Codelab_Android_Design_Support_Library.html [翻]Andro ...
- Android Design Support Library 的 代码实验——几行代码,让你的 APP 变得花俏
原文:Codelab for Android Design Support Library used in I/O Rewind Bangkok session--Make your app fanc ...
- 【代码】Android: 怎样设置app不被系统k掉
有一种方法可以设置app永远不会被kill,AndroidManifest.xml 中添加: android:persistent="true" 适用于放在/system/app下 ...
- 添加静态路由 route add -host 子网掩码 -- 在线解析
1.215 ----- R(172.16.0.1) <--------- gw(61.146.164.109) | ...
- 开启路由转发 - route add -net 0.0.0.0 netmask 0.0.0.0 gateway 192.168.0.131 window tracert 追踪路由
1.登录方式内网访问172.28.101.0/19网段的方法:在192.168.1.0/24网段的上网机器上,或在自己的操作机上加个192.168.1.0网段的ip,注意不要跟别人设置的冲突了,并添加 ...
- 使用route add添加路由,使两个网卡同时访问内外网
route add命令格式:route [-f] [-p] [Command] [Destination] [mask Netmask] [Gateway] [metric Metric] [if I ...
- route add提示: "SIOCADDRT: No such process
解决方法如下: 原因: There are multiple known causes for this error: - You attempted to set a route specific ...
随机推荐
- C++ Bit Fields
http://msdn.microsoft.com/en-us/library/ewwyfdbe%28v=vs.71%29.aspx Note An unnamed bit field of widt ...
- C#后台程序与HTML页面中JS方法互调(功能类似于Ajax中的DWR)
此方法适用于 C#中嵌入WebBrowser(浏览器) 通过浏览器中加载的页面与C#的后台代码进行交互. 一.C#程序 1.在C#窗体中添加WebBrowser(浏览器),将页面的URL添加到浏览器中 ...
- [Angular2 Router] Understand the Angular 2 Base href Requirement
The <base href=”/”/> you define will determine how all other assets you plan on loading treat ...
- Spring MVC 3.0 深入
核心原理: . 用户发送请求给服务器.url:user.do . 服务器收到请求.发现DispatchServlet可以处理.于是调用DispatchServlet. . DispatchServle ...
- android调用系统相机拍照并保存在本地
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import j ...
- cocos2d-x中CCScale9Sprite的另一种实现
cocos2d 2.0之后加入了一种九宫格的实现,主要作用是用来拉伸图片,这样的好处在于保留图片四个角不变形的同时,对图片中间部分进行拉伸,来满足一些控件的自适应(PS: 比如包括按钮,对话框,最直观 ...
- iOS和android游戏纹理优化和内存优化(cocos2d-x)
1.2d游戏最占内存的无疑是图片资源. 2.cocos2d-x不同平台读取纹理的机制不同.ios下面使用 CGImage,android和windows下是直接调用png库.我测试了下,使用png库直 ...
- 终端I/O之终端标识
历史沿袭至今,在大多数UNIX系统中,控制终端的名字是/dev/tty. POSIX.1提供了一个运行时函数,可被用来确定控制终端的名字. #include <stdio.h> char ...
- Ubuntu下VSFTPD(四)(vsftpd其它主要设置)
vsftpd 服务器的其它主要设置 : 1 .最大传输速率设置: 设置匿名用户的最大传输率为20Kbps,修改/etc/vsftpd/vsftpd.conf 添加语句:anon_max_rate=20 ...
- 类string的构造函数、拷贝构造函数和析构函数
原文:http://www.cnblogs.com/Laokong-ServiceStation/archive/2011/04/19/2020402.html 类string的构造函数.拷贝构造 ...