Home  >  Article  >  Backend Development  >  Further analysis of the Symfony control layer

Further analysis of the Symfony control layer

不言
不言Original
2018-06-08 14:54:571748browse

This article mainly introduces the Symfony control layer, and combines a large number of example codes with an in-depth analysis of the common usage skills and related precautions of the Symfony controller. Friends in need can refer to the following

This article provides an in-depth analysis of the Symfony control layer. Share it with everyone for your reference, the details are as follows:

The control layer in Symfony contains the code that connects business logic and performance. The control layer is divided into several different parts for different uses.

1. The front-end controller is the only entry point to the application
2. Actions contain the logic of the application. They check the integrity of the request and prepare the data required by the presentation layer
3. Request, Response and Session objects provide access to request parameters, response parameters, and persistent user data, which are commonly used in the control layer
4. Filters are part of the code that is executed for each request, whether before the action or After the action. You can create your own filters.

Front-end controller

All WEB requests will be captured by the front-end controller. The front-end control is the only entrance to the entire application in a given environment. point. When the front-end control receives a request, it uses the routing system to match the action name and module name of the URL entered by the user. For example:

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

URL calls the index.php script (that is, the front-end controller), which is understood as: action-myAction , module-mymodule

Working details of the front-end controller

The front-end controller distributes requests, he only executes those common and common codes, including:

1. Define core constants
2. Locate the symfony library
3. Load and initialize the core framework class
4. Load configuration information
5. Decode the request URL and obtain the content to be executed Actions and request parameters
6. Special 404 error if action does not exist
7. Activate filter (e.g., if authentication is required)
8. Execute filter, first time
9. Execute the action and submit the view
10. Execute the filter for the second time
11. Output the response.

Default front-end controller

The default front-end controller is called index.php. In the WEB/ directory of the project, it is a simple PHP file, as follows:

getController()->dispatch();

This file has been introduced before: first define a few variables, then introduce the application configuration config.php, and finally call dispatch() of sfController (which is the core controller object in the symfony MVC architecture) method. The last step will be captured by the filter chain.

Call another front-end controller to replace the environment

There is a front-end controller for each environment, and the environment is defined in the SF_ENVIRONMENT constant.

Creating a new environment is as easy as creating a new front-end controller. For example, you need a staging environment so that your application can be tested by customers before going online. To create a staging environment, copy web/myapp_dev.php to web/myapp_staging.php, and then change the SF_ENVIRONMENT constant to staging. Now, you can add staging sections to all configuration files needed to set up the new environment, see the following example:

## 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

Batch file

You need to use a batch file when accessing symfony classes and features from the command line or scheduled tasks. The beginning of the batch file is the same as the beginning of the front controller - except for the distribution part of the front controller.

Actions

Action is the heart of the application because it contains all application logic. They use the model and define variables to the view. When using a request in an application, an action and request parameters are defined in the URL.

Action class

Action is a method named executeActionName in the moduleNameActions class (inherited from the sfActions class). It is organized into modules. The module action class is stored in the actions directory. actions.class.php file.

Only files in the WEB directory can be accessed externally. Front-end control scripts, pictures, style sheets and JS files are public. Even if the methods in PHP are not case-sensitive, they are in symfony, so don’t forget Action methods must begin with execute in lower case, followed by the action name with the first letter in capital letters.

If the action class becomes large, you should do some decomposition and put the code in the model layer. Actions should be kept as short as possible (a few lines are best), and all business logic should be placed in the model layer. middle.

Optional action class syntax

You can have one action and one file. The name of the file is the action name plus Action.class.php, and the class name is the action name plus Action. , just remember that the class inherits from sfAction and not sfActions.

Getting information in actions

The action class provides a way to access controller-related information and core symfony objects. The following demonstrates how to use:

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
 }
}

Context:

A call to sfContext::getInstance() in the front controller. In actions, the getContext() method is singleton (i.e. all calls are to the first instance, which is useful for storing an index to the symfony core object associated with a given request).

sfController:控制器对象 (->getController())
sfRequest:请求对象 (->getRequest())
sfResponse:响应对象 (->getResponse())
sfUser:用户Session对象 (->getUser())
sfDatabaseConnection:数据库链接 (->getDatabaseConnection())
sfLogger:日志对象 (->getLogger())
sfI18N:国际化对象(->getI18N())
可以在代码的任何位置放置sfContext::getInstance()。

动作终止

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

return sfView::SUCCESS;

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

# 将调用indexSuccess.php模板
public function executeIndex()
{
 return sfView::SUCCESS;
}
# 将调用listSuccess.php模板
public function executeList()
{
}

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

# symfony将查找actionNameError.php模板
return sfView::ERROR;

调用自定义视图

# symfony将查找actionNameMyResult.php模板
return 'MyResult';

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

return sfView::NONE;

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

public function executeIndex()
{
 echo "Hello, World!";
 return sfView::NONE;
}
// 等价方法
public function executeIndex()
{
 return $this->renderText("Hello, World!");
}

有些时候你需要发送空的响应但包含定义的头信息(特别是X-JSON头),定义头通过sfResponse对象,并且放回sfView::HEADER_ONLY常量:

public function executeRefresh()
{
 $output = '<"title","My basic letter"],["name","Mr Brown">';
 $this->getResponse()->setHttpHeader("X-JSON", '('.$output.')');
 return sfView::HEADER_ONLY;
}

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

$this->setTemplate('myCustomTemplate');

跳向另一个动作

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

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

① 向前(Forwards)方式

$this->forward('otherModule','otherAction');

② 重定向(Redirection)方式

$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()方法):

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()之前和之后执行。

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'POST'#getHttpHeader('Server')##getCookie('foo')CookieRequest##Is the parameter In the request there is ##getParameter(' foo')Path informationWhere does it come from? ##Array( [0] => fr [1] => fr_FR [2] => en_US [3] => en )##getCharsets()##getAcceptableContentTypes()

方法名

Function

##Input example

Request Information

##getMethod()

Request

Object

Returns sfRequest::GET or sfRequest::POST constants

getMethodName()

Object Name

Given the value of the
HTTP

header

'Apache /2.0.59 (Unix) DAV/2 PHP/5.1.6'

Specifies the value of the name

' Is bar'

##isXmlHttpRequest()*

yes

AJAX
Request?

true

##isSecure()

Is it SSL

true

##Request Parameters

#hasParameter('foo')

##true

The value of the specified parameter

'bar'

##getParameterHolder()->getAll()

All request parameters Array of

##URI-Related Information

##getUri()

Full

URI

##'http://localhost/ myapp_dev.php/mymodule/myaction'

##getPathInfo()

'/mymodule/myaction'

getReferer()**

'http://localhost/myapp_dev.php/'

getHost()

Host name

'localhost'

getScriptName()

Front-end controller path and name

'myapp_dev.php'

##Client Browser Information

##getLanguages()

List of acceptable languages

List of acceptable character sets

Array( [0] => ISO-8859-1 [1] => UTF-8 [2] => * )

Array of acceptable content types

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

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对象提供了访问和移动这些文件的手段:

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对象能够跨请求地保存用户属性

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()方法访问,可以使用基本参数仓库方法很简单的清除用户属性:

class mymoduleActions extends sfActions
{
 public function executeRemoveNickname()
 {
  $this->getUser()->getAttributeHolder()->remove('nickname');
 }
 public function executeCleanup()
 {
  $this->getUser()->getAttributeHolder()->clear();
 }
}

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

Hello, getAttribute('nickname') ?>

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

Flash属性

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

$this->setFlash('attrib', $value);

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

$value = $this->getFlash('attrib');

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

has('attrib')): ?>
 get('attrib') ?>

或者

get('attrib') ?>

Session管理

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

客户端,Session被Cookies处理(handle)。Symfony的Session Cookie叫做symfony,可以在factories.yml中修改。

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

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

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文件来决定

all:
 .actions:
  login_module:      default
  login_action:      login
  secure_module:     default
  secure_action:     secure

授权

为某用户授权:

class myAccountActions extends sfActions
{
 public function executeLogin()
 {
  if ($this->getRequestParameter('login') == 'foobar') //判断根据具体需求而定
  {
   $this->getUser()->setAuthenticated(true);  //设置用户为已认证
  }
 }
 public function executeLogout()
 {
  $this->getUser()->setAuthenticated(false); //设置用户为未认证
 }
}

在动作中处理凭证:

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可以访问的动作。凭证也经常用来在模板中显示授权信息

  • hasCredential('section3')): ?>

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

复杂的凭证

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

editArticle:
 credentials: [ admin, editor ]       # admin 和 editor
publishArticle:
 credentials: [ admin, publisher ]      # admin 和 publisher
userManagement:
 credentials: [[ admin, superuser ]]     # admin 或者 superuser

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

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

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

验证和错误处理方法

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

看个例子,当一个用户请求myAction,symfony首先去查找validateMyAction()方法,如果找到了就执行,根据返回结果来决定如何往下走:如果返回真则executeMyAction()被执行,否则handleErrorMyAction()被执行,并且,如果找不到handleErrorMyAction,symfony则去查找普通handleError方法,如果还不存在则简单返回sfView::ERROR并递交myActionError.php模板,看下图:

说明:

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

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

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

看段代码:

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过滤器。

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

class myFilter extends sfFilter
{
 public function execute ($filterChain)
 {
  // 在动作之前执行的代码
  ...
  // 执行下一个过滤器
  $filterChain->execute();
  // 在动作之后执行的代码
  ...
 }
}

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

rendering: ~
web_debug: ~
security: ~
# 在这里插入你自己的过滤器
cache:   ~
common:  ~
flash:   ~
execution: ~

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

自定义过滤器链的方法:

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

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(例子)

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包含,使用下面的语句:

return $this->getContext()->getController()->forward('mymodule', 'myAction');

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

过滤器激活及参数

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

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

class rememberFilter extends sfFilter
{
 public function execute ($filterChain)
 {
   ...
   if ($request->getCookie($this->getParameter('cookie_name')))
   ...
 }
}

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

all:
 enable_remember_me: on

过滤器示例

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

class sfGoogleAnalyticsFilter extends sfFilter
{
 public function execute($filterChain)
 {
  // 在动作之前什么也不做
  $filterChain->execute();
  // 使用下面的代码修饰响应
  $googleCode = '

';
  $response = $this->getContext()->getResponse();
  $response->setContent(str_ireplace('', $googleCode.'',$response->getContent()));
  }
}

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

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

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

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。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于ThinkPHP的控制器解析

The above is the detailed content of Further analysis of the Symfony control layer. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn