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!

Dependency Injection

Dependency Injection is a widely used design pattern. We will define the concepts of this pattern and show a popular PHP implementation with a simple example.

What is DI?

Dependency Injection is a software design pattern that implements Inversion of control by decoupling software modules, introduced by Martin Fowler.

Usually a dependency injection container is used to manage and automate the construction and lifetimes of interdependent objects.

di_uml

Design pattern explanation and Use

Basically, if your class needs an object of other class, in this pattern you pass the dependency object as a constructor parameter or via property setters, instead of invoke factory or create dependency. You make it someone else’s problem.
Example 1:
class MyClass {
    private $objectA;
    public function __construct(ObjectA $object) {
        $this->objectA = $object;
    }
}
Example 2:
class MyClass {
    private $objectA;

    public function setObjectA(ObjectA $object) {
        $this->objectA = $object;
    }
}

In both examples, we don’t care how or where to create the objectA we just use it.

Some popular PHP DI-Container implementations

  • PHP-DI: is an interesting implementation of DI Container that has integration with several frameworks and IDEs like PHPStorm.
  • Symfony DependencyInjection: The DependencyInjection component allows you to standardize and centralize the way objects are constructed in your application.
  • Zend – DI: DI Container implementation for Zend framwork.
  • Pimple: Is a Dependency Injection Container from SensioLabs.

Pimple Presentation

This is an implementation from SensioLabs, and you guessed it, the same guys that created the Symfony libraries.

This is a friendly implemented package, lightweight and easy to use.
To install you just need to add to your composer.json,
$ ./composer.phar require pimple/pimple ~3.0
and you’re ready to use it!
$container = new \Pimple\Container();
Since it implements \ArrayAccess interface, you can store variables and factories as it was an array.
example of parameters:
$container['cookie_name'] = 'SESSION_ID';
an example of factory as a closure:
$container['session'] = $container->factory(function ($c) {
    return new Session($c['session_storage']);
});
It also provides methods to protect parameters, modify services after defined, extends, and more.
For more info refer to Pimple site.

Example Use Cases

Let’s imagine that we want to create factories dynamically based on a JSON configuration like this:
auth_config1
Then we can create a Trait with a method that will fill our container based on an argument that could be an array create from the decode of above JSON.
traits_builder
Here’s how we can use this trait:
di_using
Let’s break down the example above:
the class that implements the __construct method has defined a member attribute, container, that is an instance of Pimple.
Since we are using traits to buildAuthenticator, the result of the foreach block will be assigned into the class container attribute.
Within the build, we need to create a new temporary Pimple object. This is a hack I found to store nested containers.
This is needed because otherwise each time you attempt to add a sub-item within the “AUTHENTICATION” it overrides the previous one.
So once we have created all factories, we just set the temporal container in “AUTHENTICATION” cell of the main container.
To use your created object in the container you just need to do something like that:
$auth = $this->container["AUTHENTICATION"]["mock"];
$result  = $auth->doSomething();

Final Thoughts

This pattern is very useful and widely used these days especially in modern web development, in particular if you see it used in the Angular framework.
Even when you should pick the product that better match your requirements in each case, I can say that I feel very comfortable with Pimple. As I showed, it is very flexible, allowing you to create your own wrap class to customize its behavior and fit your needs.
Hope you enjoyed! Thanks for reading and see you on next posts!

Angular 2 Animations

Animations are a very important part of User Experience design for web applications. We’ll will explore how animations are created and configured in Angular 2 and provide some concrete examples.

Introduction

Continuing on our series of Angular 2, we’re now going to explore  animations in Angular 2. Clearly smooth animation and transitions are an important part of the UX design for interactive applications.

Let’s start off by talking about how we animated things in Angular 1.x.

Animations in Angular 1

Angular 1.x allowed for animations between states for a handful of directives and elements, which when coupled with the nature of an Angular application, presented some great results. Two methods were provided to allow the user to add these transition states: CSS and Javascript. While both methods had some pros and cons, it also led to different interfaces that could easily confuse a developer.

CSS transitions were provided simply by using CSS3 transitions, which have the benefit of not requiring additional JS libraries and are as fast as your browser can render. Most of the control of this style of animation is controlled by using a unique class name structure and Angular handles a class change based upon a unique naming scheme.

The ngAnimate module provided a Javascript interface to control animations. This module allowed the user to use (most likely) jQuery’s animation controls or a 3rd party JS lib to render animations. This has some benefits of allowing some fine grain control, but you were also limited to what the 3rd party library allowed you.

Animations in Angular 2

Angular 2 uses the Web Animations API to really let your browser control animations with the highest possible performance and timing control.

Unlike Angular 1.x’s interface, the entire animation library is contained within a single module. This allows for a common simple interface, but since it uses the Web Animation API, also allows the browser to optimize the animation control to a finer control that previously allowed by CSS3 only animations.

While I should note that this also requires a compatible browser to run these animations, there is a polyfill available to cover legacy browsers that is easily installed.

Let’s explore some of the basic concepts used for defining and controlling Angular 2 animations.

Triggers

Triggers are the term for a function that defines the states and transitions used for an animation. These are defined in the component annotation metadata fields and have a corresponding placement on a component’s template to indicate where an animation is applied when the end user interacts with the application.

Here’s an example of triggers defined in a simple component, and explains where we put the settings we explain later in this post:

animations: [
  trigger(
    'pState', 
    [
      state('inactive', style({
        transform: 'scale(.9)'
      })),
      state('active', style({
        fontWeight: "bold",
        transform: 'scale(1)'
      })),
      transition('active => inactive', animate('50ms ease-out')),
      transition('inactive => active', animate('50ms ease-in'))
    ]
  )
]

States

States are a defined condition, or a specific point in time by, that you can define in your Angular 2 component via a string. These finite conditions allows you to define a value you can pass into your components template to help set up your animation conditions. Examples of these states are “active” and “inactive” that can identify an element that is “On”. See our first example for a demonstration of these states.

Timing

Timing in Angular 2 is defined by three properties: duration, delay and easing

Duration controls how long an animation runs. Defined by a string or an integer in milliseconds or seconds, it’s never been easier to define the length of time a transition occurs. Here’s an example of a duration of two seconds “2s” and 200 milliseconds “200ms”.

Delay, much like you assume, is about the time that elapses between the trigger execution an the start of the animation. You can even define the delay in the same line you define the duration in this example where it last two seconds after a delay of 3 seconds: “2s 3s”

Easing is how angular controls the animation accelerates and decelerates during it’s runtime and is a pretty succinct way to add some ‘realism’ to your animation. Identified by a string, these have the same common names as the control parameter in CSS3. Some more information can be found here on this site, easings.net.

Callbacks

Callbacks are just methods called when an animation starts and stops. This is useful for executing code based on an animation’s timing, and if you have ever tried to chain commands together using browser timing alone, you will seriously jump for joy.

Here’s an example from the official angular guide with the callback methods “animationStarted” & “animationDone”:

...
  <li>
    (@flyInOut.start)="animationStarted($event)"
    (@flyInOut.done)="animationDone($event)"
    [@flyInOut]="'in'" >
    {{hero.name}}
  </li>
...

 

Example 1: P Tag State on Button Click

Our first example shows hows we can animate the two states (Active & Inactive) of a displayed P tag. Keeping this simple, we illustrate how to set up a component to use the animation library and how to set up two simple states and their transitions.

Click the gif of the plnkr below to see the code in an active plnkr:

ex_1-p_tag

Example 2: Multi-Step Animation with Callbacks

Our second example shows a multistep animation that uses keyframes to add multiple steps to a transition, and callbacks that output the start and end of each animation to the console.

Check out this plnkr, and open your console, to see this in action:

ex_2-multi-step

Conclusion

Animations add so much to web applications that it’s a mistake not to include them. Thankfully Angular 2 makes this easier to include and trigger your animations with minimal work from the developer.