Categories

Archives

Month: January 2017

This tutorial will show you how to code a simple JSON API using Opulence PHP. We will install Opulence’s skeleton project using composer, then create a ‘user’ database entity, and finally we will match CRUD (Create, Read, Update, Delete) to POST, GET, PUT, and DELETE.

Installing

The default Opulence app name is Project. Using apex, rename it to SimpleApi.

cd SimpleApi
php apex app:rename Project SimpleApi

This command will output:

JSON Config

According to the documentation if a client does not request JSON then HTML will be returned. This is “the right way to do it” but for the sake of this API we always want to return JSON. We can do this by adding the following code to config/http/views.php:

Open src/SimpleApi/Application/Bootstrappers/Orm/OrmBootstrapper.php and register an ID generator for \SimpleApi\User

private function registerIdGenerators(IIdGeneratorRegistry $idGeneratorRegistry)
{
// Register your Id generators for classes that will be managed by the unit of work
$idGeneratorRegistry->registerIdGenerator(
\SimpleApi\User::class,
new \Opulence\Orm\Ids\Generators\IntSequenceIdGenerator('user_id_seq')
);
}

Database Mapper

Using apex, create a SQL data mapper named User. When prompted pick SQL data mapper and use \SimpleApi\User as the entity.

php apex make:datamapper User

This command will output:

Open the newly created src/SimpleApi/Infrastructure/Orm/User.php and finish the stubs.

Controller Creation

Using apex, create a Controller named User. When prompted pick REST controller.

php apex make:controller User

This command will output:

Open the newly created src/SimpleApi/Application/Http/Controllers/User.php and finish the stubs. Type-hint any objects your controller needs in the controller’s constructor. Create a generic repository object for \SimpleApi\User.

PHP7 is a general purpose scripting language well suited for web development. Composer is the defacto package manager for PHP7. This tutorial will show you how to install PHP7 and Composer on Windows 10 for use in a command prompt.

A common misconception is that you need a web server like IIS, Apache, or Nginx to get started with PHP7 development. In fact, PHP7 has its own built in web server that you can invoke at the command prompt. Modern PHP frameworks such as Opulence, Symfony, Cake, Laravel, WordPress, and many more support this.