1. New package directory
Create a directory with a name of the package. I will call it laravel-log-enhancer
.
1 |
mkdir laravel-log-enhancer && cd laravel-log-enhancer |
2. composer.json
Every package starts with a composer.json
file. Let’s create it. The easiest way to create it is to fire the init
command.
1 |
composer init |
Or you can just copy it from this stub and make changes accordingly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
{ "name": "package/name", "description": "This islaravel package", "type": "library", "license": "MIT", "authors": [ { "name": "YourName", } ], "minimum-stability": "dev", "require": {}, "autoload": { "psr-4": { "package\\name\\": "src/" } } } |
Commit the change. Not compulsory but we will do it after each unique step as a good habit.
4. Namespace and autoloading
We will put the main code of our package in src
directory.
1 |
mkdir src && cd src |
5. Update composer.json file
1 2 3 4 5 6 |
"autoload-dev": { "psr-4": { "Tests\\": "tests/", "package\\name\\": "main_package_dir/packagedir/src/" } }, |
6. Create new file in src dir packagedirServiceProvider.php and update this
1 |
composer dump-autoload |
We will use it in our case to load the default configuration options of the package as well as offer an option to export those config options to the parent Laravel web app.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php namespace package\name; use Illuminate\Support\ServiceProvider; class LaravelLogEnhancerServiceProvider extends ServiceProvider { /** * Publishes configuration file. * * @return void */ public function boot() { $this->publishes([ __DIR__.'/../config/laravel_log_file.php' => config_path('laravel_log_file.php'), ], 'laravel-log-file-config'); } /** * Make config publishment optional by merging the config from the package. * * @return void */ public function register() { $this->mergeConfigFrom( __DIR__.'/../config/laravel_log_file.php', 'laravel_log_file' ); } } |
The code is quite simple here. In the boot
method, we put the code to allow the developer to export the config options by simply writing:
1 |
php artisan vendor:publish -tag=laravel-log-file-config |
And in the register
method, we tell the Laravel app to add the config options from our file into the web app config. Commit the update and let’s create our config file next.
Config options:
As a part of the convention, we will put our config file in config
directory inside root folder next to src directory.
1 |
mkdir config && cd config && touch laravel_log_file.php |
Put the following code in the file.
1 2 3 4 5 6 7 8 |
<?php return [ 'log_request_details' =>true, 'log_input_data' => true, 'log_request_headers' => false, 'log_session_data' => true, 'log_memory_usage' => false, 'log_git_data' => false, // You can specify the inputs from the user that should not be logged 'ignore_input_fields' => ['password', 'confirm_password'], ]; |
Leave a reply