I read many times about controller code mustn't be too complicated and so on. I was developing new features in my simple project. I added a function, which allow users to get access to news only in one specified category. Now, if a user writes some of this URL:
/news/common /news/sport /news/finance
only news from specified category would be shown.
I was thinking about how to do this through another actions, but realized that I can do it in index
action. I need just to check if user entered category, but not id
(id
can
contain only digits), which I've done.
Controller:
public function indexAction() {
$objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$options = array();
$categoryUrl = (string)$this->params('category');
if($categoryUrl) { // add category to the 'where'
$category = $objectManager
->getRepository('\News\Entity\Category')
->findOneByUrl($categoryUrl);
if(!$category) {
return $this->redirect()->toRoute('news');
}
$options['category'] = $category->getId();
$categoryName = $category->getName();
}
$news = $objectManager
->getRepository('\News\Entity\Item')
->findBy($options, array('created'=>'DESC'));
$items = array();
foreach ($news as $item) {
$buffer = $item->getArrayCopy();
$buffer['category'] = $item->getCategory()->getName();
$buffer['user'] = $item->getUser()->getDisplayName();
$items[] = $buffer;
}
$view = new ViewModel(array(
'news' => $items,
'categoryName' => $categoryName,
));
return $view;
}
What I am doing here?
- receive
category
from URL- if
category
specified I add clause to the$options
array and set$categoryName
as category name - if
category
is not specified I don't do anything with$options
(so it will be blank after this part) and don't set flag (so it is not set, undefined)
- if
- get news items (function pass
$options
array) - return
$categoryName
andnews
array to the view
View:
<?
if($categoryName) {
$title = $categoryName;
} else {
$title = "News list";
}
$this->headTitle($title);
?>
// html code, some conditions etc
There is an if
condition. If $categoryName
is specified, $title
will have the same contents as $categoryName
. If $categoryName
is not specified, $title
will be just News list
.
Questions
- Is this the correct approach at all? Should I create new actions and handle this case in it?
- Is it correct to set flags, as I did, send to the view, handle it etc?
- Is my controller "fat" now?
- How can I improve this code?
In addition, you can find the full code of files on GitHub:
- NewsController.php (controller)
- index.phtml (view)
Note: Some words in files are in Russian.