Reputation: 725
I feel I repeat myself in Laravel (4) controllers. For example, I need some $variables
for every view. I get them from cache or database. Because geting and processing them take some lines of codes (between 5-100 lines), I repeat them in every controller function. This is especially a problem when updating functions (They increase complexity).
How can I avoid this without any negative effect?
Note: $variables
are mostly not global variables.
Upvotes: 1
Views: 251
Reputation: 5825
Create a trait
with a method to set all of the necessary variables.
use View;
trait SharedControllerVariables {
public function loadUsersSubscription() {
View::make('user_subscription_variable_1', [...data...]);
View::make('user_subscription_variable_2', [...data...]);
}
}
Then call it in your controller constructor:
class MyController extends Controller {
use SharedControllerVariables;
public function __construct() {
$this->loadUsersSubscription();
}
}
Upvotes: 0
Reputation: 9381
You can create a static helper class (all static functions) e.g.
class VarHelper {
public static function getVars() {
return [];
}
}
You can create your own basecontroller you extend in every other controller e.g.
class MyController extends Controller {
public function getVars() {
return [];
}
}
class BlaController extends MyController {
public function doBla() {
$vars = $this->getVars();
}
}
creating the function inside the controller and call it in the other functions
use a Trait
Upvotes: 1
Reputation: 50777
There are many ways to go about this, but it sounds like the variables are more specific to your View's than your controllers.
You can easily share variables across your views in the boot
method of your AppServiceProvider
.
view()->share('variables', function(){
//you can share whatever you want here and it will be availble in all views.
});
Upvotes: 1