You should move that code into a service. Like that you can access your method like this:
$expense = $this->get('expenseFinder')->findExpense($id);
The advantage over your current method is that all your code logic would be stored in one single file. So maintaining it will be easier. Also you should never use the echo
method inside your Controllers
. Render an appropriate template instead or throw an exception. For your case the HttpNotFoundException
seems to be the right choice.
if(!$this->expense){
throw new HttpNotFoundException();
} else {
return $this->expense = $this->expense[0];
}
Create a expenseFinder.php
in src/[Your Company]/[Your Bundle]/Util
.
class expenseFinder {
protected $em;
public function __construct(EntityManager $em) {
$this->em = $em;
}
public function findExpense($id) {
// your logic here...
}
}
And register your service in the app/config/config.yml
services:
expenseFinder:
class: [Your Company]\[Your Bundle]\expenseFinder
arguments: [@doctrine.orm.entity_manager]
Now you can call it as described in the beginning of my post.