Php Symfony,在route方法中获取参数
我有个问题 以下是我的路线方法:Php Symfony,在route方法中获取参数,php,symfony1,doctrine,Php,Symfony1,Doctrine,我有个问题 以下是我的路线方法: book_list: url: /api/books.:sf_format class: sfDoctrineRoute options: { model: Book, type: list, method: getActiveWithAuthor } param: { module: book, action: list, sf_format: json } requirements: sf_format:
book_list:
url: /api/books.:sf_format
class: sfDoctrineRoute
options: { model: Book, type: list, method: getActiveWithAuthor }
param: { module: book, action: list, sf_format: json }
requirements:
sf_format: (?:json|html)
运行中的代码很简单:
public function executeList(sfWebRequest $request) {
$this->books = $this->getRoute()->getObjects();
}
以及获取书籍的自定义方法
public function getActiveWithAuthor(array $parameters) {
// crit is easy to find in logs.
sfContext::getInstance()->getLogger()->crit(var_export($parameters, true));
return BookQuery::create()
->addSelf()
->addAuthor()
->execute();
}
问题是,我想通过可选参数“date_from”过滤书籍,该参数可以在url中,例如/api/books?date_from=2011-02-18
但在日志中我只能看到“sf_format=>html”(或json)
获取可选参数“date_from”时应使用什么?您可以从请求对象获取参数:
sfContext::getInstance()->getRequest()->getParameter('date_from');
更新
更好的解决方案,无需sfContext::getInstance():
在routing.yml中指定该类的用法,您可以直接在方法中使用该参数。使用var_export($array,ture)而不是foreach hack。哦,来吧!你真的需要单件吗?@Dziamid:目标是使用路线的方法选项。@Dziamid:我也读过,但OP要求的是一些没有它很难实现的事情。如果你能做到这一点,那么就提出你的解决方案,但你目前提出的解决方案使用的是行动,而不是路线。不过,我想这可能是通过使用自定义路由实现的。在模型中使用sfContext::getInstance()-不好的做法,因为它不适用于测试。@maectpo:我在上一篇评论中发布了一个链接,阅读它,您会发现它是可行的,但需要做很多事情。我同意,这是一种不好的做法,但“您只想使用$this->books=$this->getRoute()->getObjects();”。但是看看sfObjectRoute类,我就是这么做的。但是我只想使用$this->books=$this->getRoute()->getObjects();如我所见,在我的例子中,我不能在route方法中使用$parameters。参数必须在url中定义为/:slug/:date\u from/:id或其他内容。我放弃了,用那种方法。
public function executeList(sfWebRequest $request)
{
$this->books = Doctrine::getTable('Book')-> getActiveWithAuthor($request->getParameter('date'));
}
//BookTable.class.php
public function getActiveWithAuthor($date)
{
$q = $this->createQuery('b')
->leftJoin('b.Author')
->where('b.date > ?', $date);
return $q->execute();
}
public function executeList(sfWebRequest $request)
{
$this->books = Doctrine::getTable('Book')-> getActiveWithAuthor($request->getParameter('date'));
}
//BookTable.class.php
public function getActiveWithAuthor($date)
{
$q = $this->createQuery('b')
->leftJoin('b.Author')
->where('b.date > ?', $date);
return $q->execute();
}