代码研磨 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#完成超酷的图像效果 (附demo)
如果您觉得C#制作的艺术字比较好玩, 但是还觉得没看够,不过瘾,那么我今天就让您一饱眼福, 看看C#如何制作的效果超酷的图像. (注: 我之前曾写过类似的文章, 但没有原理说明, 代码注释不够详细, ...
- linux下oracle11g R2的启动与关闭监听、数据库
su - oracle 切换到oracle账户 lsnrctl start 启动监听 sqlplus /nolog 登陆sqlplus conn /as ...
- eclipse添加第三方源码
- MySQL 多会话之间更新数据的小实例
1:创建一个实验表 mysql> use test; mysql> CREATE TABLE t -> (id int(11) NOT NULL DEFAULT 0, -> n ...
- ASP.NET Jquery+ajax上传文件(带进度条)
效果图 支持ie6+,chrome,ie6中文文件名会显示乱码. 上传时候会显示进度条. 需要jquery.uploadify.js插件,稍后会给出下载 前台代码 <%@ Page Langua ...
- 利用FluorineFX录制音频与视频
要做一个完整的录制程序,处理RPC请求的类不仅要继承ApplicationAdapter,还要继承IStreamService接口,该接口定义了play(),pause(),publish(),cre ...
- 【JavaScript】父子页面之间跨域通信的方法
由于同源策略的限制,JavaScript跨域的问题,一直是一个比较棘手的问题,为了解决页面之间的跨域通信,大家煞费苦心,研究了各种跨域方案.之前也有小网同学分享过一篇“跨域,不再纠结” 开始照着尝试时 ...
- 安装luinxWEB
Webmin的安装很简单,下面就详细说一下安装步骤. 1.用ssh客户端软件登陆服务器2.切换目录到root下,命令是:cd /root/3.下载Webmin的安装文件,命令是:wget http:/ ...
- Java虚拟机工作原理具体解释
一.类载入器 首先来看一下java程序的运行过程. 从这个框图非常easy大体上了解java程序工作原理.首先,你写好java代码,保存到硬盘其中.然后你在命令行中输入 javac YourClass ...
- 文件写入文件分布式系统(asp.net C#)
) { try { System.Drawing.Image img = System.Drawing.Image.FromStream(fileData.InputStream); &&am ...