服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - PHP教程 - Symfony控制层深入详解

Symfony控制层深入详解

2020-12-30 15:48wow_1904 PHP教程

这篇文章主要介绍了Symfony控制层,结合大量实例代码深入分析了Symfony控制器的常见使用技巧与相关注意事项,需要的朋友可以参考下

本文深入分析了symfony控制层。分享给大家供大家参考,具体如下:

symfony中控制层包含了连接业务逻辑与表现的代码,控制层为不同的使用分成了几个不同的部分。

1. 前端控制器是指向应用的唯一入口
2. 动作包含了应用的逻辑,他们检查请求的完整性并准备好表示层需要的数据
3. 请求、响应和session对象提供访问请求参数、响应参数以及持久的用户数据,这些数据在控制层使用的很普遍
4. 过滤器是每个请求都要执行的代码的一部分,无论在动作前还是在动作后。可以自创过滤器。

前端控制器

所有web请求都将被前端控制器捕获,前端控制是给定环境下整个应用的唯一入口点。当前端控制接到一个请求,他使用路由系统匹配用户输入的url的动作名和模块名。例如:

http://localhost/index.php/mymodule/myaction

url调用了index.php脚本(也就是前端控制器),他被理解为:动作-myaction,模块-mymodule

前端控制器的工作细节

前端控制器分发请求,他仅执行那些通用的和共同的代码,包括:

1. 定义核心常量
2. 定位symfony库
3. 载入和初始化核心框架类
4. 载入配置信息
5. 解码请求url,获取要执行的动作和请求参数
6. 如果动作不存在则专项404错误
7. 激活过滤器(比如,如果需要身份认证)
8. 执行过滤器,第一次
9. 执行动作,递交视图
10. 执行过滤器,第二次
11. 输出响应。

默认前端控制器

默认前端控制器叫作index.php,在项目的web/目录,他是一个简单的php文件,如下:

?
1
2
3
4
5
6
7
<?php
define('sf_root_dir'realpath(dirname(__file__).'/..'));
define('sf_app',     'myapp');
define('sf_environment', 'prod');
define('sf_debug',    false);
require_once(sf_root_dir.directory_separator.'apps'.directory_separator.sf_app.directory_separator.'config'.directory_separator.'config.php');
sfcontext::getinstance()->getcontroller()->dispatch();

这个文件在前面已经介绍过了:首先定义几个变量,然后引入应用的配置config.php,最后调用sfcontroller(这是symfony mvc架构中的核心控制器对象)的dispatch()方法。最后一步将被过滤器链捕获。

调用另一个前端控制器来更换环境

每个环境存在一个前端控制器,环境定义在sf_environment常量中。

创建新环境就和创建新的前端控制器一样简单,比如,你需要一个staging环境以使你的应用上线之前可以被客户测试。要创建staging环境,拷贝web/myapp_dev.php到web/myapp_staging.php,然后修改sf_environment常量为staging。现在,你可以在所有的配置文件中增加staging段了设置新环境所需要的东西,看下面的示例:

?
1
2
3
4
5
6
7
8
9
10
11
## app.yml
staging:
 mail:
  webmaster:  dummy@mysite.com
  contact:   dummy@mysite.com
all:
 mail:
  webmaster:  webmaster@mysite.com
  contact:   contact@mysite.com
##查看结果
http://localhost/myapp_staging.php/mymodule/index

批处理文件

在命令行或者计划任务中访问symfony类和特性的时候需要使用批处理文件。批处理文件的开头与前端控制器的开头一样——除了前端控制器的分发部分不要。

?
1
2
3
4
5
6
7
<?php
define('sf_root_dir'realpath(dirname(__file__).'/..'));
define('sf_app',     'myapp');
define('sf_environment', 'prod');
define('sf_debug',    false);
require_once(sf_root_dir.directory_separator.'apps'.directory_separator.sf_app.directory_separator.'config'.directory_separator.'config.php');
// 添加批处理代码

动作(actions)

动作是应用的心脏,因为他包含了所有应用的逻辑。他们使用模型并定义变量给视图。当在应用中使用一个请求,url中定义了一个动作和请求的参数。

动作类

动作是modulenameactions类(继承自sfactions类)中名为executeactionname的方法,以模块组织在一起,模块动作类存储在actions目录的actions.class.php文件中。

只有web目录下的文件能够被外部访问,前端控制脚本、图片、样式表和js文件是公开的,即使php中方法不区分大小写,但symfony中区分,所以不要忘了动作方法必须以小写execute开始,紧跟着是首字母大写的动作名。

如果动作类变得很大,你应该做一些分解并把代码放在模型层,动作应该尽量的保证短小(几行最好),所有的业务逻辑都应该放在模型层中。

可选的动作类语法

可以一个动作一个文件,文件的名称为动作名加action.class.php,类名为动作名加action,只是记得类继承自sfaction而非sfactions。

在动作中获取信息

动作类提供了一种访问控制器相关信息与核心symfony对象的方法,下面演示了如何使用:

?
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
<?php
define('sf_root_dir'realpath(dirname(__file__).'/..'));
define('sf_app',     'myapp');
define('sf_environment', 'prod');
define('sf_debug',    false);
require_once(sf_root_dir.directory_separator.'apps'.directory_separator.sf_app.directory_separator.'config'.directory_separator.'config.php');
class mymoduleactions extends sfactions
{
 public function executeindex()
 {
  // retrieving request parameters
  $password  = $this->getrequestparameter('password');
  // retrieving controller information
  $modulename = $this->getmodulename();
  $actionname = $this->getactionname();
  // retrieving framework core objects
  $request   = $this->getrequest();
  $usersession = $this->getuser();
  $response  = $this->getresponse();
  $controller = $this->getcontroller();
  $context   = $this->getcontext();
  // setting action variables to pass information to the template
  $this->setvar('foo', 'bar');
  $this->foo = 'bar';      // shorter version
 }
}

上下文:

在前端控制器中一个sfcontext::getinstance()的调用。在动作中,getcontext()方法是单例模式(即所有的调用都是第一个实例,这对于存储指向与给定请求相关的symfony核心对象的索引的情况是非常有用的)。

sfcontroller:控制器对象 (->getcontroller())
sfrequest:请求对象 (->getrequest())
sfresponse:响应对象 (->getresponse())
sfuser:用户session对象 (->getuser())
sfdatabaseconnection:数据库链接 (->getdatabaseconnection())
sflogger:日志对象 (->getlogger())
sfi18n:国际化对象(->geti18n())
可以在代码的任何位置放置sfcontext::getinstance()。

动作终止

当动作执行完成后会出现各种行为,动作方法的返回值决定视图如何被实施。sfview类的常量经常被指定与模板来显示动作的结果。如果一个默认视图被调用,动作应该以下面的代码结束:

?
1
return sfview::success;

symfony将寻找actionnamesuccess.php的模板,这是默认的行为,所以如果你忽略了return语句,symfony也将查找actionnamesuccess.php模板,空动作也将触发同样的行为,如下:

?
1
2
3
4
5
6
7
8
9
# 将调用indexsuccess.php模板
public function executeindex()
{
 return sfview::success;
}
# 将调用listsuccess.php模板
public function executelist()
{
}

如果要调用错误视图,动作将以下面语句结束:

?
1
2
# symfony将查找actionnameerror.php模板
return sfview::error;

调用自定义视图

?
1
2
# symfony将查找actionnamemyresult.php模板
return 'myresult';

如果动作不想调用模板(比如批处理和任务计划cron),可以使用下面的语句

?
1
return sfview::none;

上面情况下,视图层将被忽略,html代码可以直接在动作中输出,symfony提供了一个特殊的方法rendertext()来实现。这种情况比较适用于ajax交互。

?
1
2
3
4
5
6
7
8
9
10
public function executeindex()
{
 echo "<html><body>hello, world!</body></html>";
 return sfview::none;
}
// 等价方法
public function executeindex()
{
 return $this->rendertext("<html><body>hello, world!</body></html>");
}

有些时候你需要发送空的响应但包含定义的头信息(特别是x-json头),定义头通过sfresponse对象,并且放回sfview::header_only常量:

?
1
2
3
4
5
6
public function executerefresh()
{
 $output = '<"title","my basic letter"],["name","mr brown">';
 $this->getresponse()->sethttpheader("x-json", '('.$output.')');
 return sfview::header_only;
}

如果动作必须呈交特定模板,使用settemplate()方法来忽略return语句:

?
1
$this->settemplate('mycustomtemplate');

跳向另一个动作

有些情况下,动作以请求一个新的动作作为结束,例如,一个动作处理表单的post提交在更新数据库后通常会转向到另一个动作。另一个例子是动作别名:index动作经常是来完成显示,所以实际上是跳向了list动作。

有两种方式来实现另一个动作的执行:

① 向前(forwards)方式

?
1
$this->forward('othermodule','otheraction');

② 重定向(redirection)方式

?
1
2
$this->redirect('othermodule/otheraction');
$this->redirect('http://www.google.cn');

forward和redirect后面的语句将不会被执行,你可以理解为他们等价于return语句。他们抛出sfstopexception异常来停止动作的执行

两者的区别:forward是内部的处理,对用户是透明的,即用户不会感觉到动作发生了变化,url也不会更改。相反,redirection是动作的真正跳转,url的改变是最直接的反映。

如果动作是被post提交表单调用的,你最好使用redirect。这样,如果用户刷新了结果页面,post表单不会被重复提交;另外,后退按钮也能很好的返回到表单显示页面而不是一个警告窗口询问用户是否重新提交post请求。

forward404()方法是一种常用的特殊forward,他跳到“页面无法找到”动作。

经验说明,很多时候一个动作会在验证一些东西后redirect或者forward另一个动作。这就是为什么sfactions类有很多的方法命名为forwardif(), forwardunless(), forward404if(), forward404unless(), redirectif(), 和 redirectunless(),这些方法简单地使用一个测试结果参数true(那些xxxif()方法)或false(那些xxxunless()方法):

?
1
2
3
4
5
6
7
8
9
10
public function executeshow()
{
 $article = articlepeer::retrievebypk($this->getrequestparameter('id'));
 $this->forward404if(!$article);
}
public function executeshow()
{
 $article = articlepeer::retrievebypk($this->getrequestparameter('id'));
 $this->forward404unless($article);
}

这些方法不仅仅是减少你的代码行数,他们还使得你的程序更加易读。

当动作调用forward404()或者其他类似方法,symfony抛出管理404响应的sferror404exception异常,也就是说如果你想显示404信息,你无需访问控制器,你只是抛出这个异常即可。

模块中多个动作重复代码的处理方式

preexecute()与postexecute()方法是一个模块中多个动作共同的东西。可以在调用executeaction()之前和之后执行。

?
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
class mymoduleactions extends sfactions
{
 public function preexecute()
 {
  // 这里的代码在每一个动作调用之前执行
  ...
 }
 public function executeindex()
 {
  ...
 }
 public function executelist()
 {
  ...
  $this->mycustommethod(); // 调用自定义的方法
 }
 public function postexecute()
 {
  // 这里的代码会在每个动作结束后执行
  ...
 }
 protected function mycustommethod()
 {
  // 添加自己的方法,虽然他们没有以execute开头
  // 在这里,最好将方法定义为protected(保护的)或者private(私有的)
  ...
 }
}

访问请求

getrequestparameter(“myparam”)方法常用来获取myparam参数的值,实际上这个方法是一系列请求调用参数仓库的代理:getrequest()->getparameter(“myparam”)。动作类使用sfwebrequest访问请求对象,通过getrequest()访问他们的方法。

sfwebrequest对象的方法

 

方法名
功能
输入示例
request information
 
 
getmethod()
request对象
returns sfrequest::get or sfrequest::post constants
getmethodname()
request对象名
'post'
gethttpheader('server')
给定http头的值
'apache/2.0.59 (unix) dav/2 php/5.1.6'
getcookie('foo')
指定名称cookie的值
'bar'
isxmlhttprequest()*
是否是ajax请求?
true
issecure()
是否是ssl请求
true
request parameters
 
 
hasparameter('foo')
参数是否在请求中有
true
getparameter('foo')
指定参数的值
'bar'
getparameterholder()->getall()
所有请求参数的数组
 
uri-related information
 
 
geturi()
完整uri
'http://localhost/myapp_dev.php/mymodule/myaction'
getpathinfo()
路径信息
'/mymodule/myaction'
getreferer()**
来自那里?
'http://localhost/myapp_dev.php/'
gethost()
主机名
'localhost'
getscriptname()
前端控制器路径与名称
'myapp_dev.php'
client browser information
 
 
getlanguages()
可接受语言的列表
array( [0] => fr [1] => fr_fr [2] => en_us [3] => en )
getcharsets()
可接受字符集的列表
array( [0] => iso-8859-1 [1] => utf-8 [2] => * )
getacceptablecontenttypes()
可接受内容类型数组
 

 

sfactions类提供了一些代理来快速地访问请求方法

?
1
2
3
4
5
6
7
8
9
10
class mymoduleactions extends sfactions
{
 public function executeindex()
 {
  $hasfoo = $this->getrequest()->hasparameter('foo');
  $hasfoo = $this->hasrequestparameter('foo'); // shorter version
  $foo  = $this->getrequest()->getparameter('foo');
  $foo  = $this->getrequestparameter('foo'); // shorter version
 }
}

对于文件上传的请求,sfwebrequest对象提供了访问和移动这些文件的手段:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class mymoduleactions extends sfactions
{
 public function executeupload()
 {
  if ($this->getrequest()->hasfiles())
  {
   foreach ($this->getrequest()->getfilenames() as $filename)
   {
    $filesize = $this->getrequest()->getfilesize($filename);
    $filetype = $this->getrequest()->getfiletype($filename);
    $fileerror = $this->getrequest()->hasfileerror($filename);
    $uploaddir = sfconfig::get('sf_upload_dir');
    $this->getrequest()->movefile('file', $uploaddir.'/'.$filename);
   }
  }
 }
}

用户session

symfony自动管理用户session并且能在请求之间为用户保留持久数据。他使用php内置的session处理机制并提升了此机制,这使得symfony的用户session更好配置更容易使用。

访问用户session

当前用户的session对象在动作中使用getuser()方法访问,他是sfuser类的一个实例。sfuser类包含了允许存储任何用户属性的参数仓库。用户属性能够存放任何类型的数据(字符串、数组、关联数组等)。

sfuser对象能够跨请求地保存用户属性

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class mymoduleactions extends sfactions
{
 public function executefirstpage()
 {
  $nickname = $this->getrequestparameter('nickname');
  // store data in the user session
  $this->getuser()->setattribute('nickname', $nickname);
 }
 public function executesecondpage()
 {
  // retrieve data from the user session with a default value
  $nickname = $this->getuser()->getattribute('nickname', 'anonymous coward');
 }
}

可以把对象存放在用户session中,但这往往让人气馁,因为session在请求之间被序列化了并且存储在文件中,当session序列化时,存储对象的类必须已经被加载,而这很难被保证。另外,如果你存储了propel对象,他们可能是“延迟”的对象。

与symfony中的getter方法一样,getattribute()方法接受第二个参数作为默认值(如果属性没有被定义时)使用。判断属性是否被定义使用hasattribute()方法。属性存储在参数仓库可使用getattributeholder()方法访问,可以使用基本参数仓库方法很简单的清除用户属性:

?
1
2
3
4
5
6
7
8
9
10
11
class mymoduleactions extends sfactions
{
 public function executeremovenickname()
 {
  $this->getuser()->getattributeholder()->remove('nickname');
 }
 public function executecleanup()
 {
  $this->getuser()->getattributeholder()->clear();
 }
}

用户session属性在模板中默认通过$sf_user变量访问,他存储了当前的sfuser对象

?
1
2
3
<p>
 hello, <?php echo $sf_user->getattribute('nickname') ?>
</p>

如果只想在当前请求中存储信息,你更应该使用sfrequest类,他也有getattribute()和setattribute()方法,只有在请求之间持久存储信息时才适合sfuser对象。

flash属性

flash属性是一种短命属性,他会在最近的一次请求后消失,这样可以保持你的session清洁

?
1
$this->setflash('attrib', $value);

在另一个动作中获取flash属性:

?
1
$value = $this->getflash('attrib');

一旦传入了另一个动作,flash属性就消失了,即使你的session还不过期。在模板中访问flash属性使用$sf_flash对象。

?
1
2
3
<?php if ($sf_flash->has('attrib')): ?>
 <?php echo $sf_flash->get('attrib') ?>
<?php endif; ?>

或者

?
1
<?php echo $sf_flash->get('attrib') ?>

session管理

symfony的session处理特性对开发者完全掩盖了客户端与服务端的sessionid存储,当然,如果你非要去改session管理机制的默认行为也不是不可能,高级用户经常这么干。

客户端,session被cookies处理(handle)。symfony的session cookie叫做symfony,可以在factories.yml中修改。

?
1
2
3
4
5
all:
 storage:
  class: sfsessionstorage
  param:
   session_name: 自定义cookie名字

symfony的session基于php的session设置,也就是说如果希望客户端使用url参数方式取代cookies,你必须修改php.ini文件的use_trans_sid参数,不建议这么做。

在服务器端,symfony默认使用文件存储用户session,可以通过修改factories.yml文件承担class参数来使用数据库存储:apps/myapp/config/factories.yml

?
1
2
3
4
5
6
7
8
9
10
11
all:
 storage:
  class: sfmysqlsessionstorage
  param:
   db_table: session_table_name   # 存储session的表
   database: database_connection   # 数据库的名称
class名称可以是:fmysqlsessionstorage, sfpostgresqlsessionstorage和sfpdosessionstorage;后面是首选方式。
session超时的修改和调整:apps/myapp/config/settings.yml
default:
 .settings:
  timeout:   1800      #session超时 单位秒

动作的安全

动作的执行可以被限定在具有一定权限的用户。symfony为此提供的工作允许创建安全的应用,用户只有在通过认证之后才能防伪应用的某些特性或部分。设置安全的应用需要两步:定义动作需要的安全和使用具有权限的用户登录。

访问限制

在每个动作执行前都会被一个特定的过滤器来检查当前用户是否具有访问的权限,symfony中权限有两个部分组成:

① 安全动作只有被授权用户可以访问
② 凭证允许分组管理权限

通过创建或者修改config目录下的security.yml文件即可简单的完成安全访问限制。在文件中可以设置某个动作或者所有动作是否需要授权。

apps/myapp/modules/mymodule/config/security.yml

?
1
2
3
4
5
6
7
8
9
read:
 is_secure:  off    # 所有用户都可以请求read动作
update:
 is_secure:  on    # update动作只能有认证的用户访问
delete:
 is_secure:  on    # 同update
 credentials: admin   # 具有admin凭证
all:
 is_secure: off    # 无需授权

用户访问一个需要授权的动作将依据用户的权限:

① 用户已登录并且凭证符合则动作能执行
② 如果用户没有登录则转向默认登录动作
③ 如果用户已登录但凭证不符合则会转向默认的安全动作

转向将根据apps/myapp/config/settings.yml文件来决定

?
1
2
3
4
5
6
all:
 .actions:
  login_module:      default
  login_action:      login
  secure_module:     default
  secure_action:     secure

授权

为某用户授权:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class myaccountactions extends sfactions
{
 public function executelogin()
 {
  if ($this->getrequestparameter('login') == 'foobar') //判断根据具体需求而定
  {
   $this->getuser()->setauthenticated(true);  //设置用户为已认证
  }
 }
 public function executelogout()
 {
  $this->getuser()->setauthenticated(false); //设置用户为未认证
 }
}

在动作中处理凭证:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class myaccountactions extends sfactions
{
 public function executedothingswithcredentials()
 {
  $user = $this->getuser();
  // 添加凭证
  $user->addcredential('foo');
  $user->addcredentials('foo', 'admin');  //添加多个凭证
  // 判断是否具有凭证
  echo $user->hascredential('foo');           =>  true
  // 判断是否具有多个凭证
  echo $user->hascredential(array('foo', 'admin'));    =>  true
  // check if the user has one of the credentials
  echo $user->hascredential(array('foo', 'admin'), false); =>  true
  // 删除凭证
  $user->removecredential('foo');
  echo $user->hascredential('foo');           =>  false
  // 删除所有凭证 (被用在注销处理过程中)
  $user->clearcredentials();
  echo $user->hascredential('admin');           =>  false
 }
}

如果用户具有'admin'凭证,他就可以访问security.yml文件中设定只有admin可以访问的动作。凭证也经常用来在模板中显示授权信息

?
1
2
3
4
5
6
7
<ul>
 <li><?php echo link_to('section1', 'content/section1') ?></li>
 <li><?php echo link_to('section2', 'content/section2') ?></li>
 <?php if ($sf_user->hascredential('section3')): ?>
 <li><?php echo link_to('section3', 'content/section3') ?></li>
 <?php endif; ?>
</ul>

sfguardplugin插件扩展了session类,使得登录与注销的处理变得简单。

复杂的凭证

在security.yml文件中,可以使用and或者or来组合各种凭证,这样就可以建立复杂的业务流和用户权限管理系统。例如,cms系统后台办公自由具有admin凭证用户访问,文章的编辑必须有editor凭证,发布只能有有publisher凭证的用户,代码如下:

?
1
2
3
4
5
6
editarticle:
 credentials: [ admin, editor ]       # admin 和 editor
publisharticle:
 credentials: [ admin, publisher ]      # admin 和 publisher
usermanagement:
 credentials: [[ admin, superuser ]]     # admin 或者 superuser

每次添加新的[],凭证之间的关系在and和or之间切换,这样可以创建及其复杂的凭证组合关系:

?
1
2
credentials: [[root, [supplier, [owner, quasiowner]], accounts]]
       # root 或者 (supplier 和 (owner 或者 quasiowner)) 或者 accounts

注:【和】所有凭证都满足,【或】满足其中的一个凭证。

验证和错误处理方法

验证输入是重复且单调的事情,symfony提供了内置的请求验证系统,使用动作类的方法。

看个例子,当一个用户请求myaction,symfony首先去查找validatemyaction()方法,如果找到了就执行,根据返回结果来决定如何往下走:如果返回真则executemyaction()被执行,否则handleerrormyaction()被执行,并且,如果找不到handleerrormyaction,symfony则去查找普通handleerror方法,如果还不存在则简单返回sfview::error并递交myactionerror.php模板,看下图:

Symfony控制层深入详解

说明:

① validateactionname是验证方法,是actionname被请求的第一个查找方法,如果不存在则直接执行动作方法。

② handleerroractionname方法,如果验证失败则查找此方法,如果不存在则error模板被显示

③ executeactionname是动作方法,对于动作他必须存在。

看段代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class mymoduleactions extends sfactions
{
 public function validatemyaction()
 {
  return ($this->getrequestparameter('id') > 0);
 }
 public function handleerrormyaction()
 {
  $this->message = "invalid parameters";
  return sfview::success;
 }
 public function executemyaction()
 {
  $this->message = "the parameters are correct";
 }
}

可以在验证方法中加入任何代码,但最终只要返回true或者false即可。因为是sfactions类的方法,所以可以访问sfrequest和sfuser对象,这样将对于输入与上下文验证非常有利。

过滤器

安全处理可以被认为是请求到动作执行之前必须经过的一个过滤器。实际上可以在动作执行前(后)设置任意多个的过滤器。

过滤器链

symfony实际上将请求处理看作是过滤器链。框架收到请求后第一个过滤器(通常是sfrenderingfilter)被执行,在某些时候他调用下一个过滤器,依次下去。当最后一个过滤器(通常是sfexecutionfilter)执行后,前一个过滤器结束,依次返回去知道rending过滤器。

Symfony控制层深入详解

所有的过滤器均继承自sffilter类并且都包含了execute()方法,此方法之前的代码在动作(action)之前执行,此方法之后的代码在动作之后执行,看一段代码(下一节中要用到,取名myfilter代码):

?
1
2
3
4
5
6
7
8
9
10
11
12
class myfilter extends sffilter
{
 public function execute ($filterchain)
 {
  // 在动作之前执行的代码
  ...
  // 执行下一个过滤器
  $filterchain->execute();
  // 在动作之后执行的代码
  ...
 }
}

过滤器链在/myapp/config/filters.yml文件中定义:

?
1
2
3
4
5
6
7
8
rendering: ~
web_debug: ~
security: ~
# 在这里插入你自己的过滤器
cache:   ~
common:  ~
flash:   ~
execution: ~

这些声明都没有参数(~在symfony中的意思是null,将采用默认的值),他们都继承自symfony核心定义的参数,symfony为每一个过滤器(除了自定义过滤器)定义了类和参数,他们在$sf_symfony_data_dir/config/filter.yml文件。

自定义过滤器链的方法:

① 设置过滤器的enabled参数为off将禁用过滤器,例如:

?
1
2
web_debug:
 enabled: off

你还可以通过settings.yml文件达到此目的,修改web_deug、use_security、cache和use_flash的设置即可,应为每一个默认过滤器都有一个condition参数来自上面的配置。

② 不要通过删除filters.yml文件中的过滤器来禁用该过滤器,symfony将抛出异常

③ 可以自定义过滤器,但无论如何rendering必须是第一个,而execution必须是最后一个

④ 为默认过滤器重写默认类和参数(特别是修改security系统和用户的安全验证过滤器)

创建自定义过滤器

通过创建myfilter的类可以非常简单的常见自定义的过滤器,把类文件放在项目的lib文件夹可以充分利用symfony提供的自动加载特性。

由于动作之间可以互相跳转,因此过滤器链会在每一个请求中循序执行。但更多的时候可能需要是第一次请求的时候执行自定义的过滤器,这时候使用sffilter类的isfirstcall()方法。看下面代码:apps/myapp/lib/rememberfilter.class.php(例子)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class rememberfilter extends sffilter
{
 public function execute($filterchain)
 {
  // 通过调用isfirstcall方法保证只执行一次
  if ($this->isfirstcall())
  {
   // 过滤器不直接访问请求和用户对象,你需要使用context对象获取
   // you will need to use the context object to get them
   $request = $this->getcontext()->getrequest();
   $user  = $this->getcontext()->getuser();
   if ($request->getcookie('mywebsite'))
   {
    // 登入
    $user->setauthenticated(true);
   }
  }
  // 执行下一个过滤器
  $filterchain->execute();
 }
}

有时候需要在一个过滤器执行之后跳往另一个动作而不是下一个过滤器。sffilter不包含forward方法,但sfcontroller包含,使用下面的语句:

?
1
return $this->getcontext()->getcontroller()->forward('mymodule', 'myaction');

sffilter类有一个initialize方法,在对象创建的时候执行,可以在自定义的过滤器中覆盖此方法以达到更加灵活地设置参数的目的。

过滤器激活及参数

过滤器创建后还必须进行激活,在apps/myapp/config/filters.yml文件中:

?
1
2
3
4
5
6
7
8
9
10
11
12
rendering: ~
web_debug: ~
security: ~
remember:         # filters need a unique name
 class: rememberfilter
 param:
  cookie_name: mywebsite
  condition:  %app_enable_remember_me%
cache:   ~
common:  ~
flash:   ~
execution: ~

自定义过滤器中的参数可以在过滤器代码中使用getparameter方法获取:

apps/myapp/lib/rememberfilter.class.php

?
1
2
3
4
5
6
7
8
9
class rememberfilter extends sffilter
{
 public function execute ($filterchain)
 {
   ...
   if ($request->getcookie($this->getparameter('cookie_name')))
   ...
 }
}

condition参数被过滤器链测试来决定是否必须被执行。因此自定义过滤器声明能够依赖一个应用配置。要是过滤器执行,记得在应用的app.yml中加入:

?
1
2
all:
 enable_remember_me: on

过滤器示例

如果想在项目中包含特定的代码,你可以通过过滤器实现(layout方式需要在每一个应用中都要设置),看下面的代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class sfgoogleanalyticsfilter extends sffilter
{
 public function execute($filterchain)
 {
  // 在动作之前什么也不做
  $filterchain->execute();
  // 使用下面的代码修饰响应
  $googlecode = '
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
 _uacct="ua-'.$this->getparameter('google_id').'";urchintracker();
</script>';
  $response = $this->getcontext()->getresponse();
  $response->setcontent(str_ireplace('</body>', $googlecode.'</body>',$response->getcontent()));
  }
}

这不是一种好的方式,因为在非html响应中不适用,只是一个例子而已。

下个例子是转换http请求到https请求

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class sfsecurefilter extends sffilter
{
 public function execute($filterchain)
 {
  $context = $this->getcontext();
  $request = $context->getrequest();
  if (!$request->issecure())
  {
   $secure_url = str_replace('http', 'https', $request->geturi());
   return $context->getcontroller()->redirect($secure_url);
   // we don't continue the filter chain
  }
  else
  {
   // the request is already secure, so we can continue
   $filterchain->execute();
  }
 }
}

过滤器广泛地应用于插件,允许全面地扩展应用的特性。

模块配置

一些模块行为依赖配置,要修改他们必须在模块的config目录下建立module.yml并为每一个环境(或者all)定义设置。

看个例子:apps/myapp/modules/mymodule/config/module.yml

?
1
2
3
4
all:         #对所有环境
 enabled:   true
 is_internal: false
 view_name:  sfphp

enable参数允许你在模块中禁用所有动作,这样所有动作都将专项到module_disabled_module/module_disabled_action动作(定义在settings.yml)

is_internal参数定义动作只能内部调用,比如发送邮件只能有另一个动作调用而不是外部的直接调用。

view_name参数定义了view类,类必须继承自sfview。覆盖他后你将可以使用具有其他模板引擎其他的view系统,比如smarty。

希望本文所述对大家基于symfony框架的php程序设计有所帮助。

延伸 · 阅读

精彩推荐