Search code examples
phplaravelstatic-classes

Laravel : Calling functions defined in base_controller from view


In using the laravel framework, how can I call a function defined in base_controller, in a view. For exacmple:

class Base_Controller extends Controller {

    public static function format_something()
    {
         return something;
    }
}

How can i call format_something() in a view file?

Usually the error I get looks something like this: Method [link_to_action] is not defined on the View class.

Probably a silly question, but thanks in advance!

Edit

Okay! First the correct place to do something like this is in the libraries folder. Second, problem is that your class cannot have underscores.

So in application/libraries I made file AppHelper.php with class

class AppHelper {

    public static function format_something()
    {
        return something;
    }
}

And can call it like:

$formated = AppHelper::format_something;

Thanks for the help and the good forum find Boofus McGoofus.


Solution

  • This answer was written for Laravel 3. For Laravel 4 and after, Lajdák Marek's answer using Composer's autoloader is better.

    Functions like format_something() don't belong in the controller. The controller should just be about collecting data from various sources and passing it to the view. It's job is mostly just routing.

    I've created a folder called "helpers" in the application folder for all my little helpery functions. To make sure all my controllers, views, and models have access to them, I've included the following in my start.php file:

    foreach(glob(path('app').'helpers/*.php') as $filename) {
        include $filename;
    }
    

    I suspect that there's a better way to do that, but so far it has worked for me.