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.
For me is working:
Create directory "helpers" or whatever and file:
Add path to composer.json
Run: (reload the autoload)
Now you can call:
You can inspire yourself from Laravel framework itself.
I will take your example of a formatter and refer to
url
helper in Laravel Framework.Start by creating your own
helpers.php
file:And add it to your
composer.json
file:Run this command to recreate the autoload php file:
Create your service provider
app/Providers/FormatterServiceProvider.php
:Register your service provider. Laravel framework invokes
register
method but you only need to add it to your app config fileconfig/app.php
:Finally, create your actual generator class
app/Helpers/FormatGenerator.php
You can optionally create a Facade
app/Facade/Formatter.php
, to be able to doFormatter::format_that($text)
:You could ask yourself:
Formatter::format_that($text)
instead ofapp('formatter')->format_that($text)
. Sugar syntax really.Request
or want to build a complex object, the Service provider will take care of that for you and make it available in your$app
object.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:I suspect that there's a better way to do that, but so far it has worked for me.