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:
<?php
if (! function_exists('format_that')) {
/**
* Generate something
*
* @param string $text
* @return string
*/
function format_that($text)
{
return app('formatter')->format_that($text);
}
}
And add it to your composer.json
file:
"autoload": {
"files": [
"app/helpers/helpers.php"
]
}
Run this command to recreate the autoload php file:
$ composer dumpautoload
Create your service provider app/Providers/FormatterServiceProvider.php
:
<?php
namespace Illuminate\Routing;
use Illuminate\Support\ServiceProvider;
use App\Helpers\FormatGenerator;
class FormatterServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['formatter'] = $this->app->share(function ($app) {
return new FormatGenerator($app['request']);
});
}
}
Register your service provider. Laravel framework invokes register
method but you only need to add it to your app config file config/app.php
:
'providers' => [
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
// other providers...
App\Providers\FormatterServiceProvider::class,
]
Finally, create your actual generator class app/Helpers/FormatGenerator.php
<?php
namespace App\Helpers;
use Illuminate\Http\Request;
class FormatGenerator
{
protected $request;
/**
* Create a new URL Generator instance.
*
* @param \Illuminate\Routing\RouteCollection $routes
* @param \Illuminate\Http\Request $request
* @return void
*/
public function __construct(Request $request)
{
$this->request = $request;
}
public function format_that($text){
if ($request->path() == "home"){
return mb_strtoupper($text);
}
else{
return $text;
}
}
}
You can optionally create a Facade app/Facade/Formatter.php
, to be able to do Formatter::format_that($text)
:
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @see \App\Helpers\FormatGenerator
*/
class Formatter extends Facade
{
protected static function getFacadeAccessor() { return 'formatter'; }
}
You could ask yourself:
- Why the facade? You can reuse the component somewhere else by simply calling
Formatter::format_that($text)
instead of app('formatter')->format_that($text)
. Sugar syntax really.
- Why the Service provider? Dependence injections. If you need to use
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.