symfony入门学习资料之十六:Symfony框架启动过程介绍
Symfony框架的核心本质是把Request转换成Response的一个过程。从入口文件(web_dev.php)的源码可以看个大概,此文件从总体上描述了Symfony框架的工作的流程:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
从上面的代码来看,大致可以看出的程序的基本思想就是客户端发起请求,Symfony内核通过执行响应的请求,返回响应的Response结果对象,具体symfony是如何执行响应的请求的。通过下面的图可以了解个大概.
也可以通过官方文档得到下面的具体说明:
客户传入的请求由路由负责解释,并传递给返回响应对象的控制器函数。
站点的每个“页面”都在一个路由配置文件中定义,该文件将每个url映射到不同的PHP函数。每个PHP函数(称为控制器)的任务使用来自于请求的相关信息,包括Symfony提供的其他工具用来创建和返回响应对象。更进一步的说,控制器是代码所解释请求和创建响应的根源。
在大致了解了路由和控制器的工作流程基础上,再从代码上来看是如何获得Request对象的,在createFromGlobals方法内主要调用createRequestFromFactory方法。
这些参数都是通过http请求后,使用超全局变量self::createRequestFromFactory($_GET, $_POST, array(), $_COOKIE, $_FILES, $server);然后再通过构造函数实例化一个Request对象返回。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
createRequestFromFactory 顾名思义是通过工厂来创建request对象在Request的类中有$requestFactory属性,若通过自己实例化一个Request对象类,再通过setFactory()函数设置下工厂,即可以通过自定义,否则即static进行实例化。此时返回一个Request对象。
关于上面的 new static(),与new self()的区别。
self引用了发生新操作的类的方法。静态绑定是指在层次结构中调用方法的任何类。在下面代码的示例中,B从A继承了两个方法。self被绑定到A,因为它是在A的第一个方法的实现中定义的,而static被绑定到被调用的类(参看get_called_class()里的说明)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
在上面的例子代码中很容易得出:在Controller中可以通过Request对象获取相的参数,处理数据后,返回一个Response对象。下面的代码可以知道是怎样返回一个Response对象的。
详见$kernel->handle($request);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
|
此时就返回一个Response对象,发送至客户端,在页面上就可以看到其返回的内容了。