Development Environment

Learn how you can have your own local API environment.

Overview of the stack

The development environment stack we will be building is using Ubuntu 14.04, PHP 5.6, MySQL and Redis. We will be using Vagrant for the virtual server, Phinx for database migrations and composer for dependency management.

The folder structure will be as follow.

- db
  - migrations
    - 20160701190027_initial_schema.php
- public
  - .htaccess
  - index.php
- src
  - Components
    - DevConfigs.php
  - Controllers
    - Resources.php
    - Users.php
  - Managers
    - Resources.php
    - Users.php
  - Models
    - Resource.php
    - User.php
- vagrant
  - api.conf
- composer.json
- phynx.yml
- Vagrantfile
		

Setup Vagrant box

Before you get started with this, you will need to install Virtual Box, then Vagrant.

After this is done, here is the content of our Vagrantfile file.

VAGRANTFILE_API_VERSION = "2"

box = "ubuntu/xenial64"
ip = "192.168.101.101"

rootpass = "123456"

$script = <<SCRIPT

dd if=/dev/zero of=/swapfile bs=1M count=1024
mkswap /swapfile
chmod 600 /swapfile
sudo swapon /swapfile
echo "/swapfile  none  swap  defaults  0  0" >> /etc/fstab

add-apt-repository ppa:ondrej/php
apt-get update
apt-get -y install python-software-properties
apt-get update

apt-get -y install apache2
apt-get -y install php7.1
apt-get -y install redis-server
apt-get -y install php7.1-curl
apt-get -y install php7.1-mysql

debconf-set-selections <<< 'mysql-server mysql-server/root_password password #{rootpass}'
debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password #{rootpass}'
apt-get -y install mysql-server-5.7

mysql -uroot -p#{rootpass} -e "CREATE DATABASE berest;" 2>/dev/null
mysql -uroot -p#{rootpass} -e "CREATE USER 'root'@'%' IDENTIFIED BY '#{rootpass}';" 2>/dev/null
mysql -uroot -p#{rootpass} -e "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;" 2>/dev/null
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -uroot -p#{rootpass} mysql 2>/dev/null

cp /vagrant_data/vagrant/api.conf /etc/apache2/sites-available/
a2dissite 000-default
a2ensite api
a2enmod rewrite
service apache2 restart
SCRIPT

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = box

  config.vm.network "private_network", ip: ip

  config.vm.synced_folder ".", "/vagrant_data"

  config.vm.provision "shell", inline: $script
end
		

Then, the content of our api.conf file.

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName demo.berest.io

    DocumentRoot /vagrant_data/public

    <Directory /vagrant_data/>
        Options FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/api.log
</VirtualHost>
		

After these two files are created, you can type vagrant up. This will create your virtual server and provision it.

Setup dependencies

The final step is to setup dependencies using Composer.

To do this, here is the content of our composer.json file.

{
    "name": "BeRest/GettingStarted",
    "description": "BeRest Demo",
    "license": "proprietary",
    "config": {
        "vendor-dir": "vendors/composer"
    },
    "require": {
        "BeRest/API": "~1.0"
    },
    "require-dev": {
        "robmorgan/phinx": "~0.6"
    }
    "autoload": {
        "psr-4": {
            "BeRest\\GettingStarted\\": "src"
        }
    }
}

		

Once this is done, type composer install to install the dependencies.

Setup DB migrations

For database migrations, we use Phynx.

To get started type vendors/composer/bin/phynx init. This will create a file phynx.yml. This is the content of that file.

paths:
    migrations: %%PHINX_CONFIG_DIR%%/db/migrations
    seeds: %%PHINX_CONFIG_DIR%%/db/seeds

environments:
    default_migration_table: phinxlog
    default_database: development

    development:
        adapter: mysql
        host: localhost
        name: berest
        user: root
        pass: '123456'
        port: 3306
        charset: utf8
		

Then, we will add our initial schema 20160701190027_initial_schema.php. We will also add an admin user.

<?php

use Phinx\Migration\AbstractMigration;

class InitialSchema extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('users');
        $table->addColumn('email', 'string', ['limit' => 255])
              ->addColumn('password', 'string', ['limit' => 255])
              ->addColumn('permissionLevel', 'integer')
              ->addColumn('status', 'integer')
              ->addColumn('name', 'string', ['limit' => 255])
              ->addColumn('dateCreated', 'datetime')
              ->addColumn('dateUpdated', 'datetime')
              ->addIndex('email', ['unique' => true])
              ->create();

        $table = $this->table('resources');
        $table->addColumn('userId', 'integer')
              ->addColumn('name', 'string', ['limit' => 255])
              ->addColumn('dateCreated', 'datetime')
              ->addColumn('dateUpdated', 'datetime')
              ->addIndex('userId')
              ->create();

        $users = [
          [
            'email'             => 'v+admin@berest.io',
            'password'          => password_hash('123456', PASSWORD_DEFAULT),
            'permissionLevel'   => 100,
            'status'            => 1,
            'name'              => 'Admin User',
            'dateCreated'       => '2017-02-07',
            'dateUpdated'       => '2017-02-07'
          ]
        ];
        $this->insert('users', $users);
    }
}
		

Once this is done, we will apply the migration by typing vendors/composer/bin/phynx migrate.

Final Step

The final step will be to copy the content from previous steps in the public and src folders.

You now have a working local API environment!