Download the PHP package kenokokoro/laravel-basetree without Composer
On this page you can find all versions of the php package kenokokoro/laravel-basetree. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download kenokokoro/laravel-basetree
More information about kenokokoro/laravel-basetree
Files in kenokokoro/laravel-basetree
Package laravel-basetree
Short Description Initial base structure for extending while building laravel application
License MIT
Informations about the package laravel-basetree
Support
Laravel | Version |
---|---|
< 5.6 | 1.* |
5.6,5.7,5.8 | 2.* |
6.x | 3.* |
Installation
composer require kenokokoro/laravel-basetree
After the package is pulled in, register the Service Provider in your AppServiceProvider
:
That should be it.
Description
Basic multilayer structure which is basically meant for RESTful APIs and Web CRUD resources. Includes base classes which by their extending should allow working RESTful API endpoint and CRUD operations for single resource. It forces the code to be separated in business logic layer and data access layer, which results in much cleaner code.
Includes
- Error handling just by extension of the
BaseTree\Exception\LaravelHandler.php
orBaseTree\Exception\LumenHandler
-
Base controllers with required methods
a.
BaseTree\Controller\Laravel\JsonController.php
for RESTful APIs on Laravel frameworkb.
BaseTree\Controller\Lumen\JsonController.php
for RESTful APIs on Lumen frameworkc.
BaseTree\Controller\WebController.php
for web based CRUD operations on Laravel only - Base resource which is basically a class dedicated for the business logic
on given Model
BaseTree\Resources\BaseResource.php
- Generic separated classes for http or json response.
- Basic model interface which is used in every resource and data access layer
BaseTree\Models\BaseTreeModel.php
. Created models should implement this model. - Data access layer which wraps the models in separate repository for better structure and re-usability of the already used database calls. Every repository have own interface and implementation.
- Each database update is wrapped inside transaction, so if you don't receive your controllers response, and got an exception nothing will be persisted in the database.
LaravelTestCase
andLumenTestCase
which contains a lot of helpers for integration testing using the PHPUnit framework.
Usage
Requirements
-
Created migration and Model for your resource. Note that the model should extend the BaseTree model.
So in your
app\Models
directory createFoo.php
You must set the
$fillable
attribute in order to works properly. -
Create the data access layer for the created model. (Automatic creation)
For example you can create a folder under your
app
folder calledDAL
and just a folder with the model name, in this caseFoo
So in
app/DAL/Foo
createFooRepository.php
:Now the repository implementation that is implementing the newly created interface.
In
app/DAL/Foo
createEloquentFoo.php
Now bind everything in your custom created service provider. I would do:
In
app/DAL
createDalServiceProvider.php
And register the
DalServiceProvider
in yourAppServiceProvider
:With this you are done with the Data Access Layer structure. You can inject you interfaces whenever you need and reuse your queries.
-
Create the dedicated resource responsible for the business logic rules and interaction with the data access layer. Create a folder inside your
app
folder calledResources
orBLL
, and in there you can keep you model resources. (Automatic creation)In
app/BLL
create the fileFooResource.php
:With this you are pretty much done for the resource, but this package includes some helper interfaces to help you structure your validations, creating and updating.
The
BaseTree\Resources\Contracts\ResourceValidation
interface will force you to put thestoreRules()
,updateRules()
anddestroyRules()
. Having this interface implemented on your resource, your requests onstore()
,update()
anddestroy()
would be validated. If you don't need any validation for certain method, just return empty array. You can also use them as separate depending on your needs (Check theBaseTree\Resources\Contracts\ResourceValidation
, all the extended interfaces have their own method and can be used individually if needed)The
BaseTree\Resources\Contracts\ResourceCallbacks
interface contains thecreated()
andupdated()
methods which are basically hooks after resource is created or updated. Passed$dependencyAttributes
values contains everything except the$fillable
attributes that are set on your model. This is good since using this values you can easily update your relations. The callbacks also can be used individually if needed just like the resource validations that are mentioned above (BaseTree\Resources\Contracts\ResourceCallbacks
check the extending interfaces)The
$attributes
contains the$fillable
attributes. -
Now the controller. Each controller should extend the
BaseTree\Controllers\Laravel\JsonController
for laravel andBaseTree\Controllers\Lumen\JsonController
for lumen when using json andBaseTree\Controllers\Laravel\WebController
depending on your need. (Automatic creation)In
app/Http/Controllers
(or inside somewhere else) create yourFoosController.php
. -
Now you are ready for your route:
- Using the exception handler from the base-tree. In your
App\Exceptions\Handler
do the following:
Request - Response
Note that you will always have to set your Accept header to application/json
.
Having this being said, now you have RESTful API with just few classes creation:
- Visiting
/api/foos&datatable=1
will return you response which can be used as ajax source for jquery datatables plugin. - Visiting
/api/foos&paginate=1&perPage=10
will return you paginated response with next and previous urls in the response. Default value forperPage
is 15. - Visiting
api/foos&constraints[0]=name|=|bar
will return all foos with name bar. You can build query strings using the php functionhttp_build_query(['constraints' => ['name|=|bar', 'active|1']])
. - Visiting
api/foos&fields[0]=Bar
will return all foos but with theBar
relation included in the response.
The structure for the constraints value is columnName|operator|value
. If you need to add constraint
by another column: columnName|operator|`otherColumn`
Testing
This package contains database test class which can make your database required testing much easier.
-
Setup your DB_CONNECTION to testing inside
phpunit.xml
: -
Setup your testing connection inside your
database.php
config file: Inconfig/database.php
underconnections
add:This will give the ability for the
BaseTree\Tests\Traits\DatabaseMigrations
which is included insideBaseTree\Tests\LaravelDatabaseTestCase
orBaseTree\Tests\LumenDatabaseTestCase
to migrate and seed before your test start, and rollback after your test is finished. Like this you will always have fresh database.Testing models
In
tests/Models
createFooTest.php
which corresponds to yourFoo.php
Model. Let's assume that yourFoo
model has oneBar
model.
Testing controller endpoints
After you create your FoosController
which extends the DatabaseTestCase
you can:
Feeling limited with just empty files
If you need additional functionality you can always override the parent methods. For example, if you want
to generate slug for you resource which only has name as value, in your app\BLL\FooResource.php
Same thing works for controllers and DAL. Whatever you need to be customized can be extended and overwritten.
Artisan generators
-
Generate data access layer. This command will generate repository and eloquent implementation. Don't forget to bind this into your
ServiceProvider
Example:
php artisan basetree:dal --model=App\\Models\\User
-
Generate business logic layer. This will generate a resource with the repository interface injected inside your contructor
Example:
php artisan basetree:bll --model=App\\Models\\User --dal-interface=App\\DAL\\User\\UserRepository
-
Generate controller. The generated controller will have the given business logic layer injected inside the constructor
NOTE: At this point, the generator is only creating controller extending the
RestfulJsonController
. You will have to change the extension manually on the generated controller in order to extend theWebController
or create it manuallyExample:
php artisan basetree:controller --model-plural=users -bll=App\\BLL\UserResource
-
Publish the docker-compose architecture. Check out the .env.docker-compose.example for the required variables to make the docker containers just work.
Example:
php artisan basetree:boilerplates --docker-compose
Required variables:
DOCKER_HOST_UID=1000
# Your host user id. Check it by doingecho $UID
orid username
.DOCKER_HOST_GID=1000
# Your host group id. Check it by doingecho $GID
orid username
.DATABASE_LOCAL_STORAGE=/opt/mariadb/project
# Where to keep your database files on your host machine. This is required since if you rundocker-compose down -v
this will destroy the data in your database, if the storage is not mounted on your host machine.PMA_PORT=81
# Public exposed port for PhpMyAdmin. If running on QA environment or if you don't need you can remove if from thedocker-compose.yml
file, or by runningdocker-compose stop phpmyadmin
NGINX_SERVER_NAME=localhost
# The virtual host nameNGINX_PORT=80
# Public exposed port for the nginx container. Should be80
in order to avoid adding your port after your domain. Example: If yourNGINX_PORT=8080
, you will have to access it:localhost:8080
on your browser. Also if you already have some services listening to the given port, you will have to shut them down.CONTAINER_ROOT=/application
# The name of your project inside the container.DB_ROOT_PASSWORD=root-pass123
# MariaDB root passwordQA_HTTP_HOST=
# If you are running multiple docker instances, and you want to bind them all to80
port, you will have to specify thefastcgi_param HTTP_HOST
here, in order your application to redirect to your proxy url.DB_HOST=mariadb
# If you are using the docker mariadb instance, instead of your own already installed.
After all this is set up, you will have to run
docker-compose -f docker-compose.yml -f qa.docker-compose.yml -f dev.docker-compose.yml up -d
and wait for the build to finish. Check your containers status by runningdocker-compose ps
. You will have to see something like this:
Lumen support
The same explanation about laravel applies for Lumen as well, and the behaviour should be equal for lumen and laravel. The special cases for lumen are:
-
The lumen controller is not the same with the laravel controller
-
Using the exception handler from the base-tree. In your
App\Exceptions\Handler
do the following: - Database required testing
In
tests/Models
createFooTest.php
which corresponds to yourFoo.php
Model. Let's assume that yourFoo
model has oneBar
model.
TODO:
Tests for everythingArtisan generator- Wiki examples and explanations
- Include JWT support
- Add artisan single endpoint generator to wrap all generators at once
Tests:
make phpunit
To execute the tests
License
The BaseTree package is open-sourced software licensed under the MIT license
All versions of laravel-basetree with dependencies
barryvdh/laravel-ide-helper Version ^2.6
illuminate/contracts Version ^8.0
illuminate/console Version ^8.0
illuminate/container Version ^8.0
illuminate/http Version ^8.0
illuminate/support Version ^8.0
yajra/laravel-datatables-oracle Version >9