Testing a REST API with Frisby.js

When our web app depends on pulling data through a REST API, we need to test that the endpoints well. Thats where things become more complicated and tedious to do manually. Two great libraries, Jasmine.js and Frisby.js, can help us out here.

What is Frisby and how does it work?

We are software developers and we strive to write good code.  We try to ensure the quality of every line and workflow which in turn means testing.  Manual testing works to a point but without automated testing of REST APIs and Ajax endpoint regression testing becomes cumbersome.  Are you really going to test all the possibilities/permutations with Postman?  I didn’t think so.

Testing a REST API is not so different to testing modules, but to create “end-to-end” test cases we needed make real endpoints calls. A manual testing job quickly becomes a tedious task, so we need to find a way to make things automated.

Frisby is a REST testing framework built on node.js and jasmine, and makes testing API endpoints a very flexible and easy task.

As any normal npm package running in node, Frisby needs node.js installed first, after that you can install Frisby as a common package:

npm install -g frisby

By convention, the file name containing the Test Suite, should include the trailing word “_spec.js”, node.js runs in javascript so logically js is the extension.

In order to continue our intrduction we will study the roleAPI_spec.js, a test suite part of the package Users of Erdiko Framework:

var frisby = require('../node_modules/frisby/lib/frisby');

This is the “kickoff” for our test suite, we instance the library in a Frisby variable, it will be our object to along  the suite.

describe('Role api test suite', function() {
  var baseURL = 'http://docker.local:8088/ajax/users/roles/';
  /**---This case test the api response and check the result----*/

  frisby.create('Get all roles')
        .get(baseURL + 'roles')
        .expectStatus(200)
        .expectHeader('Content-Type', 'application/json')
        .afterJSON(function (response) {          
            expect(response.body.method).toBe('roles');
            expect(response.body.success).toBe(true);          
            expect(response.errors).toBe(false);
            expect(response.body.roles).toBeDefined();
        })     
        .toss()
});

All  Frisby test starts with frisby.create(‘A gently worded description of test’) and next we must specify the verb to make the call to our endpoint. It is obvious but must match with the endpoint structure.

In our case we used .get(baseURL + ‘roles’)

Differences between using post or get.

There are differences between verbs post and get. When we create post test cases, we should pass objects as arguments, let’s see an example grabbed from userAPI_spec.js from Users package of Erdiko framework:

/*---------------------------------------------------------*/
/*-----------------Create User success --------------------*/
frisby.create('Creation will success.')
 .post(baseURL + 'register',
 {"name":"NameTest",
  "email":"test@email.com",
  "password":"secret"},
 { json: true },
 post_header)
 .expectStatus(200)
 .toss()

By default, Frisby sends POST and PUT requests as application/x-www-form-urlencoded parameters. If we want to send a raw request content, we must use { json: true } as the third argument to the .post().

Using Expectations.

/**--checking creation with expectations --*/
frisby.create('Checking user created exist.')
    .get(baseURL + 'retrieve?id=' + USER_ID)
    .expectStatus(200)
    .afterJSON(function (response) {
        expect(response.body.method).toBe('retrieve');
        expect(response.body.success).toBe(true);
        expect(response.body.user.id).toBe(response.body.user.id);
        expect(response.body.user.email).toBe(newUser.email);
        expect(response.body.user.name).toBe(newUser.name);
        expect(response.body.user.role.id).toBe(newUser.role);
    })
   .toss()

In comparison with our traditional phpunit, the framework to create unit test cases in php, we could say that phpunit Asserts are analog to Frisby Expectations. In particular, we are interested by that expectations to handle json code. Because that we are use the ‘expect’ clause that compare the API response with a parameter provided by us:

expect(response.body.method).toBe('retrieve')

Here we expect that ‘response.body.method’ be equals to the string ‘retrieve’. It’s important to mention that the comparison is by type and value at same time and both should match to result ‘true’.

After explain that we have a few expectations used:

  • expectJSON( [path], json )
  • expectJSONTypes( [path], json )

Managing Headers, afterJSON()

/**-----------delete user created ----------------*/
frisby.create('removing user created.')
    .get(baseURL + 'cancel?id=' + USER_ID)
    .expectStatus(200)
    .afterJSON(function (response) {
        expect(response.body.method).toBe('cancel');
        expect(response.body.success).toBe(true);
        expect(response.body.user.id).toBe(USER_ID);
    })
   .toss()

As we said previously, Frisby is an extension of Jasmine.node, and afterJSON is a very good evidence because afterJSON is the extension of after() with the convenience of parse the body obtained as response as JSON values automatically. The ‘after’ occurs immediately after the response is sent from the endpoint call and is used as a callback.

Using inspectors, inspectJSON()

Inspector helpers are useful for viewing details about the HTTP response when the test does not pass, or has trouble for some reason. They are also useful for debugging the API itself as a more user-friendly alternative to curl.

// Console output
{ url: 'http://theurl/get?foo=bar',
    headers:
    { 'Content-Length': '',
        'X-Forwarded-Port': '80',
        Connection: 'keep-alive',
        Host: 'httphost.org',
        Cookie: '',
        'Content-Type': 'application/json' },
    args: { foo: 'bar'},
    origin: '127.0.0.1' }

Basically inspectJSON() prints the raw HTTP response, other similar and general inspectors are:

  • inspectBody()
  • inspectHeaders()
  • InspectRequest()
  • InspectStatus()

Conclusion

Frisby makes it possible to write end-to-end tests with a lot of flexible tools and the process of test a complete REST API turns fun and easy. We miss the ability to ‘serialize’ test cases as in a regular test unit framework. Given the nature of javascript its possible to chain nested test cases and mimic, in some aspect, that behaviors.

We haven’t tried Newman yet, but hope to soon.  Let us know about your Frisby (and Newman) experiences.

Introducing the Erdiko User Admin

Introducing the Erdiko User Admin Package! A user administration package built with an Erdiko powered backend and a Angular 2 frontend.

We’re excited to introduce the Erdiko User Admin! A modular package that provides an attractive UX to allow you to manage your users.

This is still very much a work in progress, but since we’re so excited, we want to let everyone know about this project (and request some help to keep us moving).

Check out our User Admin Project at this Github Repository and our Packagist entry.

Project Features

We wanted to create a modular and simple User Admin you can ‘bolt-on’ a new or existing project. We keep this as lean and mean as we could, but still providing some cool stuff to help get you started.

While this package is still very much in development, it does provide some of the following features:

  • A sortable and paginated list of user records.
  • An attractive user interface allowing the user to create, edit & delete user records
  • JWT user authentication!

Here’s some screenshots of our UX:

Installation and Setup

The User Admin package is a part of the Erdiko module ecosystem. Installable and upgradable via Composer. This makes it very simple to start a new project via this simple command.

composer create erdiko/user-admin [PROJECT NAME]

Please note that as of this time, we have not created an official release. You will need to include the minimum stability flag when you create your project:

composer create erdiko/user-admin [PROJECT NAME] --stability DEV

Package Dependencies

Here’s a brief list (and a bit of a plug) of some of the other Erdiko Packages we as a team have been developing that we use to build this project. While we use these packages for our development, we have planned to make these as modular and replaceable as we can.

Here’s the list:

  • erdiko/core
    • The base package that provides our basic routing and templating.
  • erdiko/authenticate
    • Authenticate the user’s credentials to assert they are who they say they are.
  • erdiko/authorize
    • A package that helps us enforce some user roles.
  • erdiko/users
    • Our Erdiko package that provides the backend storage and basic routes we use to interact with these models.

AngularJS 2

We utilize the great Angular CLI project to start and maintain the Angular code itself. This project was a great boon to help us get started on a well structured and maintainable Angular application.

The internal structure is “just” a simple app, but we have updated the NPM script to compile and move the resulting files to an directory accessible to the Erdiko application Home route.

NPM Run Scripts

Here is a quick list and an explanation of some of the custom NPM run commands we have for this project.

  • Start the local Angular Development server: npm run start
  • Run the unit tests: npm run test
  • Run the e2e/functional tests: npm run e2e
  • Compile and export files for end user: npm run build

Next Steps

Here’s an incomplete list of some of the next things we plan on working on, and completing, with the project in the future:

  • Jasmine Unit Tests to cover our angular code
  • KarmaJS Functional Tests to cover the entire application end-to-end
  • A basic User facing profile designed for user extension

How to Contribute

If you have an idea for a new feature, have an idea on how to improve a feature, or (gasp) you have found a bug please report this on our Github Repo Issues page.

However if you are just excited about this project, feel free to “star” this repo on Github to show your support.

We would also love to know if and how you use this module in your own projects!

To set your environment up for local development, please follow these steps:

  1. Clone your fork of the User Admin project into a local directory
  2. Clone the following packages into the same directory
  3. Copy the composer-dev.json file to composer.json
  4. Start your docker container docker-composer up --build

Conclusion

Thanks for reading about our exciting new package! Feel free to leave a comment or ask questions below, or feel free to comment on our Github Repo page!

Themes in the Erdiko Framework (Part 2)

In the first post we talked about how themes works in the Erdiko framework and covered important files to configure it. We continue with more advanced Erdiko theme topics and introduce new classes to discover more features, including layouts.

Today, I’m going to show you more concepts around themes in the Erdiko framework.  There are more concepts and classes to know and understand.

Layouts

To introduce the Layout class we need to define what is a layout: it includes the HTML for a basic web application structure in order to provide your own content. After made this clarification, we realize that a layout could be made by one, two, three or whatever number of columns.

Let’s look at the next code from Erdiko framework:

/**
 * Get two column layout example
 */
public function getTwocolumn()
{
    // Set columns directly using a layout
    $columns = array(
        'one' => $this->getView('examples/one'),
        'two' => $this->getView('examples/nested_view')
        );
    
    $this->setTitle('2 Column Layout');
    $this->setContent($this->getLayout('2column', $columns));
}

This code is an action from Example controller from code base of Erdiko framework. We can see how passing an array of views we can get a new layout built with ‘2column’ parameter. This way we instruct to Example controller what design we want to set to our application, and the final result will be something like this:

2columns

It’s important to take care about this latest parameter, it must exist as layout in the layout’s folder and the name must match exactly. Let’s recall our Erdiko folder structure:

layouts

the key method is Controller->getLayout():

 $this->setContent($this->getLayout('2column', $columns));

Under the hood, the controller delegates to a new Layout object composed of 2 views (one for each column) the call to render html code:

return  $layout->toHtml();

Pages

In order to reuse code the framework gives the chance of include html code often used, i.e. Header and Footer. This kind of content normally stay static around  the application. When we say “static” talk about structure however we also could include mustache code within the pages by using the {{ variable }} sintaxis.

Header

The header is a good example of html code that probably will not change in our web app. Erdiko framework installation provides us a nice default html code in the file:
app/themes/bootstrap/templates/pages/header.html

Something interesting to comment is the next piece of code:

<div class="navbar-collapse collapse" id="navbar-main">
  <ul class="nav navbar-nav">
    {{# menu.main }}
        <li>
            <a href="{{href}}">{{title}}</a>
        </li>
    {{/ menu.main }}
  </ul>
</div>

Ok, what is that sort of tag “menu.main”? Don’t worry just let’s say that we can create a html menu programmatically. When we talk about “Regions” will expand a better explanation. One important thing to highlight: the menu is built from the key “menu” in application.json file.

Footer

Footer section is more or less the same concept we talked previously with “header” but applied to the footer of application. Erdiko framework provides a default footer, the big difference against Header is the region used:

<div class="col-lg-12">
        <ul class="list-inline">
            <li class="pull-right"><a href="#top">Back to top</a></li>
            {{# menu.footer}}
                <li><a href="{{href}}">{{title}}</a></li>
            {{/ menu.footer}}
        </ul>
        <p>{{site.copyright}} {{site.full_name}}<br />
           Powered by <a href="https://github.com/ArroyoLabs/erdiko"
                         target="_blank">Erdiko</a>
        </p>
</div>

This time, the region used is ‘main.footer’ and the key used from application.json is “menu.footer”.

FlashMessages

To conclude with pages, another great and useful example is FlashMessages that provides (and being redundant) a flash message on top of the header page and denotes something important to show to the user application.

Unlike Header and Footer, FlashMessages is a helper, and you can call it:

<?php $messages = \erdiko\core\helpers\FlashMessages::get() ?>

‘$messages’ is an array and you are able to loop around it in order to give html structure:

<?php foreach($messages as $message): ?>
   <div class="alert alert-<?php echo $message['type'] ?> 
     alert-dismissible" role="alert">
     <button type="button" class="close" 
             data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
    </button>
    <?php echo $message['text'] ?>
   </div>
<?php endforeach ?>

If you can get messages, it’s logic that you can set messages too 😉 :

<?php 
$message ='This is a success message to show.';
//what color we want to show the message? 'danger' is by default.
$type = 'success';
\erdiko\core\helpers\FlashMessages::set($message,$type);
?>

Regions

In the first post when we talked about Mustache we understood how a content is rendered exactly in the right position into the html code. In order to conceive Regions, we can take the same concept, regions is just a “mark” in the html code to teach the framework about what kind of html structure we want to create, just in the right position where should be placed.

Let’s take the region part of footer.html:

 {{# menu.footer}}
     <li><a href="{{href}}">{{title}}</a></li>
 {{/ menu.footer}}

When the framework process this region tag, as result we will get a nice footer created programmatically. The million dollar question is:
– How the framework makes possible to know about footer structure?
Easy, Erdiko reads the section ‘menu.footer’ and iterates the key/values within  in application.json file.

Scripts and Styles

Previously, in our post “sample application using Erdiko Framework” we proposed as example a little dice to roll with a very simple view. That view used the controller method addJs() and addCss() in order to add css and js code to the view respectively. The method signature  is the next:

/**
 * Add Css includes to the page
 *
 * @param string $name
 * @param string $file
 * @param int $order
 * @param int $active
 */
public function addJs($name, $file, $order = 10, $active = 1)
{
    $this->getResponse()
        ->getTheme()
        ->addJs($name, $file, $order,$active);
}

Both methods share the same order and number of parameters.

Views

A view object is a piece of code to provide a visual representation of model data, in object terms is a very simple class where we can modularize our html code. Let’s take an example from Erdiko framework:

$this->addView('examples/about', $data);

here we add the view ‘examples/about’ to the  controller response. The views can receive parameters, here is the constructor:

public function __construct($template = null, $data = null, $templateRootFolder = ERDIKO_APP)
{
    $this->initiate($template, $data, $templateRootFolder);
    $this->setTemplateFolder('views');
}

by reading this code we can understand easy, what kind of parameters a view needs, look how the folder ‘views’ is assigned by default.

There is no more to talk about Views, the content will be rendered by the controller with addView() method internally, calling to:

$this->appendContent($view->toHtml());

Using properties

There are a set of  properties  defined and accessibles to the entire application, we can use it between {{ variableName }} in views or templates because are just keys/values already created in application.json config. file. To mention a few of them:
– site.name
– site. description
– site.copyright

Default.php

Default.php is, paradoxically, the default template theme applied to a given view. In a general manner, default.php is a complete html page with formal sections (head, body, etc) but instead make use of static code, it call the previously defined dynamic pages as header, footer and messages. Let’s see a fragment just to understand how the sections are referenced:

<?php echo $this->getTemplateHtml('header'); ?>
<?php echo $this->getTemplateHtml('messages'); ?>
<?php echo $this->getContent(); ?>
<?php echo $this->getTemplateHtml('footer'); ?>

where the method call:

$this->getContent()

what we want is to render the View code itself.

Conclusion

Erdiko framework provides a very flexible solution to easily change the aspect of a complete web application as complex as we propose it, the key to achieve that is setup properly all our config. files and templates.
Thanks for reading!

Themes in the Erdiko Framework (Part 1)

As web applications and sites become more complex it becomes important to organize your view layers with themes. We explain how to leverage the Erdiko theming engine and how to keep your code tidy and consistent. This is the first of a series of posts about Erdiko theming.

Why do we need themes?

Typically when we start a new web project, we are focused on the workflow and technical details about how the applications will work and what solution will provide to the end user. At some point of the planning process, we should start thinking about how our application will look, what data will offer, and then we begin to define our needs:

  • What is dynamic and what is static
  • What will be changed according our business logic
  • What is the menu, header, footer etc

Most of the time the HTML code will deliver rendered data elements, but half the battle of frameworks is deciding how to organize your code.

remember that design patterns are tools that you can use to solve specific problems , In MVC the Controller is responsible for determining which View is displayed in response to any action including when the application loads, if some parts of the view are very similar probably you need themes, don’t reinvent the wheel!

Currently we can find this behavior in any web application or SPA :

  • The header and footer are consistent across pages
  • The content changes according to the link we click in the navbar
  • The navbar (below the header or left aligned) will probably change according  to user level (admin, operator, visitor, etc).

At the end of the day we can realize that we don’t have to repeat over and over the same code, and we want to promote the re-usability of our code.

Thankfully, much of this work has been solved by many modern frameworks (re-inventing this is not an easy task). Let’s examine how we accomplish this with the Erdiko theming engine.

Paths and files

Let’s discuss what is in our Erdiko folder structure:

paths

For the moment just keep focusing on the “themes” folder and their nested folders. There are a lot of files right? Don’t worry let me explain:

  • themes: where each different theme is stored.
  • bootstrap: the default Erdiko’s theme.
  • views: This is where we put our HTML templates, where we render the data from our models.

Within the bootstrap theme:

  •  templates/layouts: we got templates in the most common variety: 1, 2, 3 columns and a menu.
  • templates/page: this part is the easier to understand, footer and header content, a messages file to show flash message alerts, and two special files: ‘google_header’ and ‘google_body’.  These last two allow us to insert Google Tag Manager and Google Analytics information.
  • theme.json: this file is one of the most important in order to use themes feature. Here we can set up all the previous files we talk, using json format.
  • app/config/{context}/default.json: another important config file to set up what theme will be used by the Erdiko application (theme, namespace, how many columns? And the home url). In order to demonstrate the flexibility of Erdiko framework, you can define many different contexts for a web application (default, production, etc).
  •  Default.php: the backbone file for Erdiko’s themes, here we give the main html5 structure to the final app  and also (and most important) we make use of the previous dynamic files (header, footer, example) calling the method:
Theme::getTemplateHtml().

In the same way we can show the dynamic code corresponding to the footer:

$this->getTemplateHtml('footer');

 We finally don’t know how this magic happens, how to mix dynamic data and html code in the exactly and specific parts. Is a dirty job but somebody has to do it… and the candidate is Mustache!

But what is mustache?

Mustache is a logic-less templating language that can be used to take most of the work out of creating re-usable HTML templates.

Let’s see a little example:
1. define the mustache template:

<h1>{{header}}</h1>

Please note the ‘header’ word between curly brackets.

2. define the model to user over that template:

{ "header": "Hello world!"}

3. Apply that model to the template and render it:

<h1>Hello world!</h1>

This pattern is extremely useful. Not just for re-use, but making debugging far easier.

Currently Mustache offers a lot of useful functionality but this is the most basic and important one. What we got here is the idea how it works, but remember that Mustache is One of many template systems, and the framework is not limited to use it.

Themes

The Theme class is the key element here, we need to understand how it works, their methods names are self-exaplanatory, the most important task is to process data and html templates to obtain a final html code. When a controller is created, a theme attribute is built in order to provide structure to the application. All necessary parts before to render are prepared by the _before() hook:

public function prepareTheme()
{
    $this->getResponse()
         ->setTheme(new \erdiko\core\Theme($this->getThemeName()));
}

Each time we call an action on a controller (except the ajax controllers) we automatically are setting a Theme, by inheriting the class \erdiko\core\Controller. When the action is done, tipically we create a new view passing a data array as second parameter:

$this->addView('examples/list', $data);

Or maybe we don’t want to show a view, we can just show a basic content with controller::setContent() method:

// Entering raw text on the page
$this->setContent("
    <div class=\"container\"><p>
    This is the simplest page possible.</p>
    </div>");

Then if the action is finished, the internal Theme will render their html stored. The most important methods of class Theme are:

  • addMeta(): Manages metadata of the application.
  • setPageTitle() and setBodyTitle(): Manages the title.
  • getCss() and getJs(): their setters add units of code, but the getters retrieves an array of that specific nature (array of css, or array of js stored). The result is a well formed <link> tag according to each array cell.
  • getTemplateHtml($aPartialToBeRendered): we can switch the template for a theme to render html with data.
  • toHtml(): finally we got html rendered.

In this first half of our blog post, we offer a big picture view of how theming works in Erdiko framework. At this point, we know that Controllers ‘under the hood’ already has prepared a theme ready to use with our defined content, and these themes are able of make html code. But they are not the only actors in this movie and the render concept needs to be explained a little more in depth. The next post we will continue talking about themes and discovering more actors and abilities. Thanks for reading!

Sample Application Using The Erdiko Framework

This time we will show you how to set up a quick and easy application using the Erdiko framework. You can roll the dice and try your luck!

Sometimes we need to create an application from scratch and there are a little set of things to get in mind relative to how and what we want to build: what language, to define the architecture, gather all the assets and (maybe) a long list of items more.

   A great idea is to use the Erdiko framework for building web apps quickly using well known MVC patterns and make the php deployment easy. Here we will create a little web app to roll a dice and get a result in two flavors: using a view and getting the result as AJAX call.

MVC is the separation of model, view and controller, it’s simply a paradigm; an ideal that you should have in the back of your mind when designing classes. Avoid mixing code from the three categories into one class

Roll the dice

    We took a fresh installation of Erdiko framework and created a view to the main page.Here we see 2 buttons:

  • One for go to the ‘get’ request.
  • Another one to get the same request above but using an ajax call, in this case you will not note difference into the current page after click the button because the roll result is coming in background as a json object.

 

new_main

The Model

    For the model we created a super-very-simple class with just only one method, “roll_dice”.

   This method returns a random value and it’s very easy to understand, the value will be used later to select the correct dice image and set up the view.

The Controller

erdiko_app_controller_get_dice_action

    With the goal of keep things simple, we will reuse the Example controller and added one new action: getDiceRequest(). What the action does is create a new Dice model instance and get the random value generated with the call to Dice::roll_dice(). After that, sent the result to the view to be shown in the front end.

    Also to the ajax call we will use the existing AjaxExample controller and made a very similar action: getDice().

erdiko_app_controller_ajax_get_dice_action

   What it does is mimic the action of the getDiceRequest action in Example controller but is managed in different way: the browser will never change the page and the result of the Dice::roll_dice() method is sent encapsulated in a json response.

   On the other side, the view is waiting for this json object in order to change the things quiet. Is for that reason the browser will never open a new tab or hop to a new page.

The View

   For this post finally we created 2 view, the main and the dice request. Both are purely 100% html as we can see:

erdiko_app_controller_index

    We can note how the controller knows how to insert javascript code to the final html render with the public function addJs() and is a good  “glue example”  between php world and html world, and how to keep a minimal separation of concerns.

jscode

A framework follows the Hollywood principle: “Don’t call us; we’ll call you.” It acts as a constraint that solves the particular problem it was designed to solve

    The Javascript part is not so complicated. We take the dice value and map the name of the right picture to show in the view.

    If the request is solved by backend php rendering instead of an ajax response with javascript, we just display the expected image with pure html:

dice_examples_view

Et voilà, the dice number is shown!:

dice_ajax_get_request

    I hope you enjoyed this post. You can apply good design patterns and quickly build a web app with the Erdiko framework. Thanks for reading!

https://github.com/arroyolabs-blog/roll-dice

Moving to Slim PHP

After developing Erdiko for over 4 years we are making some big changes for the next major release. We are modifying the framework to support Slim. Erdiko will soon be built on top of the great features of the Slim PHP micro framework.

We have been developing our open source micro framework for 4 years now.  We haven’t publicized it much but we’ve poured hundreds of hours into it and use it considerably on client projects. The framework and many of its modules are used and liked in the PHP community.

We are ready to take Erdiko to the next level and in the process of architecting a new Erdiko framework.  The next version will be more modular, better tested and, most importantly, built on top of an existing micro framework.

When we started Erdiko the other micro frameworks weren’t there yet, thats part of the reason we start Erdiko.  Silex and slim were in infancy, lumen didn’t exist (and Laravel was just starting to get more notice), and heck composer was less than a year old and wasn’t on many people radar yet.  Fast forward a few years and we now find a very different landscape for PHP and JavaScript development.

Speaking of this landscape, the fact that we can and do move much of the app to the front-end with powerful JavaScript frameworks means the duty of the back end has changed.  You no longer need to add ridiculous layers of front-end logic in your PHP classes and templates.  This shift alone means you need to rethink what you need from a php framework.

Thats where micro frameworks soar…places where you need a fast backend and leveraging a smarter front-end (e.g. SPA with JavaScript).  Add the great SaaS tools at your disposal as well and you have all the ingredients to make performant websites that you can grow your business with.  You don’t need a big bloated full stack in most cases.  If you do, often the built in feature X just won’t cut it and you end up integrating a 3rd party package or writing that component yourself anyways.

Now back to the topic at hand, what’s the deal with SlimPHP?  After reviewing numerous frameworks it became apparent that SlimPHP was the best of bunch for the kind of code we like, community we like and of course the kind of features and performance we like.  It’s router, http objects and flexibility has Erdiko beat.  We also looked at and experimented with Silex, lumen and some others before making the decision.

Erdiko adds the MVC and theming support to a typical micro framework.  We’ve developed some useful components and feel that adding these on top of an existing framework will make development even more efficient and flexible.

Erdiko has some special features that will aim to make development more enjoyable and lead to better applications.  We have been distilling pieces of Erdiko that will be moved and improved to work with Slim.  Right now we feel the configuration, theme engine and controller support will make the cut.  Actually quite a bit of erdiko will exist in the new framework, but we will strive to leverage slimphp and the slim paradigm whenever possible.  On the model side we have included wrappers for powerful ORMs so that developers can pick the best one for the job and install with one command.

Headless WordPress (A Primer)

What is headless

There are many great open source software packages out there.  Some of the most popular are WordPress, Drupal and Magento.  It has been gaining popularity in recent years to run these apps as headless.  But what does that mean?

Running headless means to use the admin and data collected in an app but use something else to render the front-end.  For instance you could manage all of your content in the wordpress admin but site that the end user sees is rendered in some other technology all together.

At the end of the day the websites that we visit are all HTML, CSS and JavaScript.  Behind the scenes the story get more complex.  Since all your data has been crafted in wordpress you can pull this content out and render it in your favorite

Who is it for?

So why would I decapitate my WordPress site?

Let me start by who it is not for.  If you are using wordPress and have no problems with how your site currently acts or functions than headless is not for you.

If you run a WordPress site but are having issues with scaling, security, and customizations than it is definitely something you should take a look at.  Keep reading 🙂

 

Why headless WordPress

Advantages
There are many advantages to using an app (CMS) like WordPress headless.  To start it allows you take full control of your front-end.   More importantly it allows you to compose your site using the latest front-end technologies of your choosing.  Love Angular, React or some old Famous animation; then use it in a clean way and don’t be stuck trying to use it in a way that only some random module says it can be used.

Use can use pure bootstrap (or Foundation) [add links]
Easily integrate JavaScript
If you hate PHP you are not stuck with it, you can use Node.js, RoR, Python or any other language and framework you choose.
Improved security (if you use a more secure front-end)
Improved
It is much easier than it sounds
You can more easily mix wordpress content with non-wordpress content
I’ve done demos using both
Potential for a richer UI/UX and faster browsing
SPA, turn your blog into a single page app and impress your friends

[links to other posts]

Disadvantages
Out of the box WordPress has an easy to use user front-end and numerous themes available for free or cheap on the web.  This

You can no longer use all those free wordpress themes
it does take more than casual programming
For a large site that has lots of content and numerous plugins, going headless could be a little time consuming
If are trying to use both wordpress and Drupal 7 (or lower) you have to use one via an API
I did some experiments in 2014 bootstraping both together and there are just too many conflicts.  Things may be different with Drupal 8

Basic headless

How to get headless working

In order to go headless you need to include wp-load.php, which is in the root of your wordpress code.  In my case I have wordpress in a folder wordpress/ which is inside lib/

define(‘WORDPRESS_ROOT’, ROOT.’/lib/wordpress’);

if ( !isset($wp_did_header) ) {

$wp_did_header = true;

require_once( WORDPRESS_ROOT . ’/wp-load.php’ );

}

after that you have WordPress running headless.

now try to pull some data.  For instance try,

$post = get_post(1); // get post is a WP function to pull a single blog post by post id

var_dump($post);

How-to with Erdiko-WordPress

going headless with Erdiko is very simple if you have composer.  In your favorite composer based framework or micro framework (Laravel, Symfony, Erdiko, Slim, etc) simply run

composer require erdiko/wordpress

you’re done.

To test it out create a route in your app and simply instantiate this model.

$wpModel = new /erdiko/wordpress/Model;

// you can call any wordpress api function for instance get_post()
$post = $wpModel->get_post(1);

var_dump($post);

https://github.com/ArroyoLabs/erdiko-wordpress

Multi-site

Multi-site works in a similar fashion, however some additional steps are needed to let WordPress know which site you are on.  Also depending on the use case there is some auto-routing you can do to make things easier.

This will be part of a future post.  It’s not as clean as the going headless on a single site.  If your multi-site is very complex you may struggle a bit running it headless.

Conclusions

Headless is great, but its not for everybody.  Keep in mind, in an enterprise scenario you either need to go headless or harden your out of the box WordPress app.

Next steps
We will post more examples and advanced use case throughout the year.  Please comment and share your thoughts if you would like to see a specific headless example.  Stay tuned!

Tutorial: Doctrine DBAL (PHP Database Abstraction Layer)

This tutorial will show you how to connect a database using Doctrine DBAL.  The examples are for Erdiko, but could be applied to any PHP framework that uses composer.

Installation

If you have not installed Erdiko, please go to http://erdiko.org/getStarted.html#installation

To install Erdiko via Composer. simply run

composer create-project erdiko/erdiko my-project-name

After you have installed Erdiko (or your other favorite framework), it is very easy to install Doctrine.

via composer:

composer require doctrine/dbal 2.3.*

Alternatively, you can do it by hand by modifying the composer.json file in the root folder.  You just need to add this line:

{“require”: {“doctrine/dbal”: “2.3.4”}}

Then run ‘composer update’ to install Doctrine DBAL.

Basic usage

1. Getting a connection

We can get a connection through the DoctrineDBALDriverManager class.

$connectionParams = array(
    ‘dbname’ => ‘database_name’,
    ‘user’ => ‘user_name’,
    ‘password’ => ‘user_password’,
    ‘host’ => ‘localhost’,
    ‘driver’ => ‘pdo_mysql’
);
$conn = DoctrineDBALDriverManager::getConnection($connectionParams, $config);

Now, you are ready to retrieve and manipulate data.

2. Data Retrieval And Manipulation

After you have established a connection with database, it is easy to manipulation data.

In this tutorial, we create a table “Products" and create three fields for it.

The three fields are Name, Qty, and Price.

Inserting Data

$sql = “INSERT INTO Products (Name, Qty, Price) VALUES (‘Mango’, ’10’,5)”;
$stmt = $conn->query($sql);

Retrieving Data

$sql = “SELECT * FROM Products”;

$stmt = $conn->query($sql);

while ($row = $stmt->fetch()) {

    echo $row[‘Name’].’, Qty: ’.$row[‘Qty’].’, Price: ’.$row[‘Price’];

}

The output should be “Mango, Qty:10, Price:5”.

Advanced usage:

To perform fancy data manipulation or query, we will need to set up the class loader before establishing a connection.

Setting up class loader

We can open the Example controller(Example.php) under Erdiko/app/controllers/.

In the Example controller, we will need to add the following line before the class scope and it will allow the program to access the class ClassLoader.

use DoctrineCommonClassLoader;

Then, we can add the following code to a page.

$classLoader = new ClassLoader(‘Doctrine’);

$classLoader->register();

$config = new DoctrineDBALConfiguration();

Note: 

It is not a good practice to set connection parameters every time we get a connection with database.  A better way to do it would be storing all these parameters to a config file and creating a data model to read the config file.

For example, we can create a db.json config file under Erdiko/app/config/local/

In the db.json, we can set the connection parameters.

{

      “data":{       

          “dbname": ‘database_name’,

          “user": ‘user_name’,

          “password": ‘user_password’,

          “host": ‘localhost’,

          “driver": ‘pdo_mysql’

     }

}

Then, we can create a data model and it should looking something like below.

public function getDbConfig($dbConfig)

{

     $config = Erdiko::getConfig(“local/db”);

     $connectionParams = array(

         ‘dbname’ => $config[“data"][“dbname”],

         ‘user’ =>  $config[“data"][“user”],

         ‘password’ =>  $config[“data"][“password”],

         ‘host’ =>  $config[“data"][“host”],

         ‘driver’ =>  $config[“data"][“driver”],

     );

     return $connectionParams;

}

The getDbConfig function will make the program easy to maintain and also reduce the amount of code.

Now, getting a connection will be only required the following line:

$conn = DoctrineDBALDriverManager::getConnection($connectionParams, getDbConfig(‘data’));composer create-project erdiko/erdiko project-name

PHP mashups and micro frameworks

Over the last two years we’ve been developing our php micro framework.  It came out of the need for more concise theming and mashing up data sources.  This lead to the development of Erdiko.  It’s an MVC micro framework that facilitates lean stacks and cool mash-ups.  Our moto is, “Enterprise Glue.”

We developed a simple yet powerful framework to get work done quickly yet maintain efficiency on the server.  Unfortunately too many of the large php frameworks suffer from performance issues.  Its typically caused by code bloat and or too much automagic happening.  For some projects this is great, for others it just gets in the way.

image

MVC

On the view side, Erdiko supports standard php templates, markdown and handlebars.  On the controller side we package all our content to rendered through a Response object and theme and/or structure the data according to your needs.  A rest api or ajax request does not need a themed page wrapper for instance.  Structured json is preferred.

Here is an example of a coding simple page.  It sets the page title and renders a single view in the page body.  A controller method like, getHello() might look like this:

$this->setTitle(‘Hello World’);
$this->addView(‘examples/index’);

The model layer is the mash up layer.  We actually don’t include much code here intentionally.  The models should be based on what your project is trying to accomplish.  We don’t want to assume we know your data better than you do!  We will be adding support to pull data from Drupal, Magento and WordPress.  If you need an ORM or MySQL connector use Doctrine, Zend Models, or whatever works best for you.  We’ve used a number of data models in the past with erdiko.  Its great to be able to leverage some of the great PHP you already know.  We will be writing more blog posts to show you architectures and code styles that help you make a clean mash up.  We’re talking about sound engineering here, not some frankenstein monster 😉

Router

The router is based on ToroPHP which borrows the conventions from Tornado (popular Python framework).  We have the guts or Toro (single file framework of only 125 lines) underneath erdiko.  We mantain compatibility with toro yet extend it to meet the needs of erdiko.

All of the routes are defined in a simple json file with a concise syntax that supports expressions.  There are also hooks that can be used before and after controller requests

Closing

The framework is a culmination of years of software writing and working with both start ups and large enterprises.  It’s a work in progress but we use it in production and are constantly improving it.  We’ve tried a lot of different techniques and architectures, with the latest version of erdiko we did some serious rewrites and made something we’re proud of.

I hope you find it useful.  Please give us feedback, fork it, remix it, and contribute back.

Check out more at http://erdiko.org/

Erdiko Update (Bootstrap 3)

We added Bootstrap 3 support to Erdiko, https://github.com/arroyo/Erdiko

We spent a little bit of time recently refactoring the theming layer and the folder structure.  The folder structure changes took a couple of cues from frameworks like Laravel and Kohana.

We have some ideas to make Erdiko more powerful and faster, keep an eye out in the coming months.