I am a newb learning laravel 4. I want to override specific helper functions. Or add new functions to Url, Str etc. How to do this?
相关问题
- Laravel Option Select - Default Issue
- Laravel 5.1 MethodNotAllowedHttpException on store
- Laravel - Implicit route model binding with soft d
- laravel : php artisan suddenly stop working
- How to execute MYSQL query in laravel?
相关文章
- laravel create model from custom stub when using p
- send redirect and setting cookie, using laravel 5
- How to send parameters to queues?
- Bcrypt vs Hash in laravel
- Laravel: What's the advantage of using the ass
- How to make public folder as root in Laravel?
- Input file in laravel 5.2?
- What is the difference between Session::set and Se
Depending on what part of Laravel you want to extend or replace, there are different approaches.
Macros
Adding functions to Str is really easy, because of "macros":
Here's a short example for adding function:
You can then call this function as expected:
Adding functions using macros are supported by Str, Form, HTML and Response.
IOC Based Extension
To extend URL one must use the IOC of Laravel. This is explained in the docs (as mentioned by BenjaminRH). I agree it can be a bit hard to understand. Here's a step-by-step to extend URL:
Create folder app/lib to hold your extension classes.
Add this folder to autoloading:
In app/start/global.php, append the lib path to the class loader:
Then add the path to composer.json classmap:
Create the custom UrlGenerator app/lib/CustomUrlGenerator.php:
Create a service provider app/lib/CustomRoutingServiceProvider.php:
Register the service provider in app/config/app.php:
Add
CustomRoutingServiceProvider
to the providers array. For example, right after the Workbench provider:Run
composer dump-autoload
from project root folder.Done. Use like:
NOTE The code is tested, but may contain some errors
Interesting that you should mention this, actually. A whole documentation section was just recently added, which covers this in detail. It's very clear, and easy to understand. If you've been using Laravel at all, it might not even surprise you that Laravel actually provides an
extend
method for a lot of core components.Following Fnatte's answer, today's versions of Laravel do some extra processing in the
url
binding. Redefining the whole binding is no longer a practical option.Here is how I ended up for extending the
URL
facade.First, create your child class using this boilerplate:
Then, add this in a ServiceProvider:
The point is simply that the original
url
binding should be executed at least once before we override it with our own.