Symfony控制层深入详解(4)

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.'https://www.jb51.net/'.$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对象

<p> Hello, <?php echo $sf_user->getAttribute('nickname') ?> </p>

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

Flash属性

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

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

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

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

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

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

或者

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

Session管理

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/acc323a5fe49d6e20da85f99c0a4d6da.html