How to handle same code in a component and an action ?
A common question is how one can include php code, which is actually used in a component with something like a ajax call or common spoken, another action.
This article tries to show you the solution.
Imagine you have a list of news, which is fetched within an component.
<?php class newsComponents extends sfComponents{ public function executeList(){ // fetch news objects from the model } }
The according template _list.php of this component action looks like this:
<?php echo "Here is a news list.....";
Continue imagine that you want to refresh this news list within an ajax call. How do you do this without repeat yourself?
The answer is: With a kind of wrapper action, which does nothing more than including the news component.
<?php class newsActions extends sfActions { public function executeList(){ // no code is needed here // because we do all the code stuff within the included component } }
The content of the template listSuccess.php:
<?php include_component('news','list');
And you are done.
Now you can do a ajax call to news/list or include the component in another action to retrieve the same output and to run through the same php code.