Depending on which part of Laravel you want to expand or replace, there are different approaches.
Macros
Adding functions to Str is very simple because of the "macros":
Here is a quick example of adding a function:
Str::macro('test', function($str) { return 'Testing: ' . $str . '!'; });
Then you can call this function as expected:
echo Str::test('text'); // Outputs "Testing: text!"
Adding functions using macros is supported by Str, Form, HTML and Response .
IOC based extension
To extend the URL, you must use IOC Laravel. This is explained in the docs (as mentioned by BenjaminRH). I agree that this can be a little difficult to understand. Here's a step by step to expand the url:
Create a / lib folder to store your extension classes.
Add this folder to startup:
In app / start / global.php add the lib path to the class loader:
ClassLoader::addDirectories(array( app_path().'/commands', app_path().'/controllers', app_path().'/models', app_path().'/database/seeds', app_path().'/lib' ));
Then add the path to the composer.json class layout:
"autoload": { "classmap": [ "app/commands", "app/controllers", "app/models", "app/database/migrations", "app/database/seeds", "app/tests/TestCase.php", "app/lib" ] },
Create a custom application UrlGenerator / lib / CustomUrlGenerator.php:
<?php use \Illuminate\Routing\UrlGenerator; class CustomUrlGenerator extends UrlGenerator { public function test() { return $this->to('/test'); } }
Create the service provider application /lib/CustomRoutingServiceProvider.php:
<?php use \Illuminate\Routing\RoutingServiceProvider; class CustomRoutingServiceProvider extends RoutingServiceProvider { public function boot() { App::bind('url', function() { return new CustomUrlGenerator( App::make('router')->getRoutes(), App::make('request') ); }); parent::boot(); } }
Register your service provider in /config/app.php:
Add CustomRoutingServiceProvider to the providers array. For example, immediately after the Workbench provider:
'Illuminate\Workbench\WorkbenchServiceProvider', 'CustomRoutingServiceProvider',
Run composer dump-autoload from the project root folder.
Done. Use as:
URL::test();
NOTE The code is tested, but may contain some errors.
Matteus Hemström
source share