API STARTER PACKAGE

Build Status

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:

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
Options
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
Options
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
Options
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
Options
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
Options
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
Options

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.