API STARTER PACKAGE
This is a laravel package that helps you start of building a laravel API. It contains useful command generators to generate various files for your API and is completely configurable. The generators include:
starter:init
starter:model <name> --fillable[=FILLABLE] --migration --relationships[=RELATIONSHIPS] --repository --schema[=SCHEMA] --soft-deletes --table[=TABLE] --transformer
starter:migration <name> --schema[=SCHEMA] --soft-deletes --model[=MODEL]
-
starter:controller <name> --automate --except[=EXCEPT] --only[=ONLY] --plain --repository[=REPOSITORY] --resource --transformer[=TRANSFORMER]
starter:repository <name> --model
starter:transformer <name> --fields[=FIELDS] --includes[=INCLUDES] --model[=MODEL]
Installation
Step 1: Install the composer packages
Add
{
"minimum-stability" : "dev",
"prefer-stable" : true
}
to your composer.json file.
Run in terminal
composer require ralphowino/restful-api-helper 1.0.x-dev
Step 2: Add the Service Provider
Add the service provider in config/app.php
:
Ralphowino\ApiStarter\ApiStarterServiceProvider::class
Step 3: Publish the packages configuration files
Publish the package's assets by running
php artisan vendor:publish --provider="Ralphowino\ApiStarter\ApiStarterServiceProvider"
Step 4: Initialize the package
Initialize the project by running
php artisan starter:init
Select directories to save the generated files in.
NB: Just press enter for every question to retain the default.
Step 5: Generate a new jwt token
Generate a new jwt token for the application by running
php artisan jwt:generate
Usage
Commands
1. starter:init
Description
This command is used to setup the basic configurations for the package and import the starter files into your application. Guides you on setting up the basic structure for the application's folders and places to which to generate the files. It also sets up authentication for the API straight out of the box.
Arguments
No arguments for this command
Options
This command has no options for it's execution
2. starter:model
Description
This command allows you to create a model for the API it will automatically extend the Base Model that comes with the package, this is however configurable from the starter.php config file and saves the model to the set out path in the starter.php config file.
Arguments
-
name
- The name of the model class (Preferred to be singular)
Options
-
--fillable
- This option specifies the fillable fields for the model -
--migration
- This option generates a migration along with the model being created -
--relationships
- This option allows you to specify the relationships for the model -
--repository
- This option allows you to specify and create an accompanying repository for the model -
--schema
- This option sets the fields for the model and if a migration is to be created adds the fields to the migration, if no fillable fields have been define the fields are all added to the fillable array -
--soft-deletes
- This option allows you to add soft delete functionality to the model being created -
--table
- This option is used to explicitly set the table name for the model -
--transformer
- This option allows you to specify and create an accompanying transformer for the model
Example
php artisan starter:model Task --schema="title:string, description:text" --fillable="title,description" --table="tasks" --relationships="user:belongsTo, subtask:hasMany" --soft-deletes
The appropriate format for the fillable fields is:
FIELD,FIELD
The appropriate format for the relationships is:
MODEL:RELATIONSHIP
The appropriate format for the schema is:
COLUMN_NAME:COLUMN_VALUE
..the model created will be:
<?php
namespace App\Data\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Ralphowino\ApiStarter\Resources\BaseModel;
class Task extends BaseModel
{
use SoftDeletes;
/**
* The model's table
*
* @var string
*/
protected $table = 'tasks';
/**
* This are the mass assignable fields for the model
*
* @var array
*/
protected $fillable = ['title', 'description'];
/**
* Links to it's user
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Links to it's subtask
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function subtask()
{
return $this->hasMany(Subtask::class);
}
}
3. starter:migration
This command creates a new migration for the application
Arguments
-
name
- The name of the migration
Options
-
--model
- This option creates a model along with the migration -
--schema
- This option adds the fields for the migration -
--soft-deletes
- This option adds soft deletes to the migration
Example
php artisan starter:migration create_tasks_table --schema="title:string, description:text" --soft-deletes
The schema format remains the same as that of the model command
...the file generated with the command:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTasksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('tasks');
}
}
4. starter:controller
This command creates a controller for the application and extends the BaseController automatically and is saved in the specified folder in the config file although all this (Class to extend and place to save the controller) is fully configurable in the config file.
Arguments
-
name
- The name of the controller
Options
-
--automate
- This option creates all the described classes for the controller e.g. The accompanying repository and transformer -
--except
- This option defines the methods to exclude from the controller's methods -
--only
- This option describes the methods to have in the controller -
--plain
- This option does not include the resourceful trait in the controller -
--repository
- This defines the repository for the controller -
--resource
- This option creates a controller with all the resourceful methods -
--transformer
- This defines the transformer for the controller
Example
php artisan starter:controller TasksController --only="index,show"
...the controller generated by the above command:
<?php
namespace App\Http\Controllers\Api;
use Dingo\Api\Http\Response;
use Illuminate\Http\Request;
use App\Data\Repositories\TasksRepository;
use App\Http\Transformers\TasksTransformer;
use App\Http\Requests;
use Ralphowino\ApiStarter\Resources\BaseController;
class TasksController extends BaseController
{
/**
* The repository variable
*
* @var TasksRepository
*/
protected $repository;
/**
* The transformer variable
*
* @var TasksTransformer
*/
protected $transformer;
/**
* The constructor for the controller
*
* @param TasksRepository $tasksRepository
* @param TasksTransformer $tasksTransformer
* TasksTransformer are used to convert model to json, with fields we would like to show.
* TasksRepository contains all logic used to manipulate the database you can override this with
* repository class you wish to have.
*/
public function __construct(TasksRepository $tasksRepository, TasksTransformer $tasksTransformer)
{
$this->repository = $tasksRepository;
$this->transformer = $tasksTransformer;
}
/**
* Display a listing of the resource.
*
* @param Request $request
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$archived = $request->input('archived', false);
$collection = $this->repository->getPaginated($request->get('per_page', 10), $archived);
return $this->response()->paginator($collection, $this->transformer);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$item = $this->repository->getByKey($id);
return $this->response()->item($item, $this->transformer);
}
}
5. starter:repository
This command creates a repository for the application in the configured path in the configuration file.
Arguments
-
name
- The name of the model
Options
-
--model
- This option creates the model linked to the repository as it creates the repository
Example
php artisan starter:repository TaskRepository
...the repository generated is:
<?php
namespace App\Data\Repositories;
use App\Data\Models\Task;
use Ralphowino\ApiStarter\Resources\ResourcefulRepositoryTrait;
use Ralphowino\ApiStarter\Resources\BaseRepository;
class TaskRepository extends BaseRepository
{
use ResourcefulRepositoryTrait;
/**
* This is the repository's model
*
* @var Task
*/
protected $model;
/**
* TaskRepository constructor
* @param Task $task
*/
function __construct(Task $task)
{
$this->model = $task;
}
}
6. starter:transformer
This command creates a transformer for the application, the transformer is saved in the specified path in the configuration file.
Arguments
-
name
- The name of the model linked to the transformer
Options
-
--fields
- The fields to be included in the transformer -
--includes
- This are the includes for the transformer -
--model
- This option the defines the model for the transformer
Example
php artisan starter:transformer TaskTransformer --fields="name,slug" --includes="user:item, comments:collection, goal, elements"
For the fields format a comma seperated list is expected
name,user,time
For the includes the following format should be used
INCLUDE_NAME:INCLUDE_TYPE
if you do not include the INCLUDE_TYPE
the generator will try to determine if the word is plural or singular and change the type according with that
...transformer generated by the command is:
<?php
namespace App\Data\Transformers;
use App\Data\Models\Task;
use League\Fractal\TransformerAbstract;
class TaskTransformer extends TransformerAbstract
{
/**
* List of resources possible to include
*
* @var array
*/
protected $availableIncludes = ['user','comments','goal','elements'];
/**
* Turn this item object into a generic array
*
* @param Task $task
* @return array
*/
public function transform(Task $task)
{
return [
'id' => $task->id,
'name' => $task->name,
'slug' => $task->slug,
'created_at' => (String)$task->created_at,
'updated_at' => (String)$task->updated_at
];
}
/**
* Include User
*
* @param Task $task
* @return \League\Fractal\Resource\item
*/
public function includeUser(Task $task)
{
$user = $task->user;
return $this->item($user, new UserTransformer());
}
/**
* Include Comments
*
* @param Task $task
* @return \League\Fractal\Resource\collection
*/
public function includeComments(Task $task)
{
$comments = $task->comments;
return $this->collection($comments, new CommentTransformer());
}
/**
* Include Goal
*
* @param Task $task
* @return \League\Fractal\Resource\item
*/
public function includeGoal(Task $task)
{
$goal = $task->goal;
return $this->item($goal, new GoalTransformer());
}
/**
* Include Elements
*
* @param Task $task
* @return \League\Fractal\Resource\collection
*/
public function includeElements(Task $task)
{
$elements = $task->elements;
return $this->collection($elements, new ElementTransformer());
}
}
6. starter:resource
This command creates for you a resource; this contains a model, migration, repository, transformer, controller; for you application from the single resource name, you however have various options of modifying what will be generated.
Arguments
-
name
- The name of the resource
Options
-
--controller
- This option allows you to define the controller for the resource -
--except
- This option allows you to define the methods to except from the generated controller -
--fields
- This option allows you to define the fields for the transformer -
--includes
- This option allows you to define the models to include in the resource's transformer -
--model
- This option the defines the model for the transformer -
--only
- This option allows you to define the methods for the generated controller -
--relationships
- This option allows you to define the relationships for the resource's model -
--repository
- This option allows you to define the repository for the resource -
--schema
- This option enables you to specify the schema for the resource -
--soft-deletes
- This option adds soft-delete to the resource -
--table
- This option allows you to define the table's name for this resource -
--transformer
- This option allows you to define the transformer for the resource
This command is used to do each of the other commands as unit; which in this case is termed as a 'resource'; so the output is the same as the other commands individually. It is just to let you generate a resource in one quick sweep. :-)
Configuration
You can configure the destinations of the files generated by configuring the paths to the various files in the config/starter.php
configuration file
...the default config file
<?php
return [
/*
* The migration configuration settings.
*
* 1. Path - path to where the created migrations are stored
*/
'migration' => [
'path' => 'database\\migrations'
],
/*
* The model configuration settings
*
* 1. Path - path the models will be saved in.
* 2. Extends - The class all the created models will extend.
*/
'model' => [
'path' => 'Data\\Models',
'extends' => 'Ralphowino\\ApiStarter\\Resources\\BaseModel'
],
/*
* The controller configuration settings
*
* 1. Path - path the controllers will be saved in.
* 2. Extends - The class the created controller extends
*/
'controller' => [
'path' => 'Http\\Controllers\\Api',
'extends' => 'Ralphowino\\ApiStarter\\Resources\\BaseController'
],
/*
* The repository configuration settings
*
* 1. Traits configuration settings
* 1.1. Path - the path the repository traits will be saved in.
* 2. Path - the path created repositories will be saved in.
* 3. Extends - the class all created repositories will extend.
*/
'repository' => [
'trait' => [
'path' => 'Data\\Repositories\\Traits'
],
'path' => 'Data\\Repositories',
'extends' => 'Ralphowino\\ApiStarter\\Resources\\BaseRepository'
],
/*
* The transformer configuration settings
*
* 1. Path - the path the created transformers will be saved in.
*/
'transformer' => [
'path' => 'Http\\Transformers'
],
/*
* The routes configuration settings
*
* 1. Path - the path the routes file is located.
*/
'routes' => [
'path' => 'Http'
],
/*
* The default classes for the application
*
* 1. Repository - the default repository for the controllers
*/
'default' => [
'repository' => 'UsersRepository',
'transformer' => 'UsersTransformer'
]
];
Star our repository if this if you like this package. Share you views on the package to help us improve on it.
Written with StackEdit.