Good architecture and why not to render Controllers inside Views

In Symfony, Zend and other frameworks you can rend a controller inside a view like this:

{{ render(controller('AcmeArticleBundle:Article:recentArticles', { 'max': 3 })) }}

 Creating and Using templates documentation here.

Just because there is a possibility to render(ControllerMethod,{ params}) in a template doesn’t mean you have to use it.

Doing so leads almost always to a shitty architecture, the turning point where projects start to be hard to debug, since you are mixing a VIEW (Presentation layer) with a CONTROLLER, that in turn renders another VIEW. You get the point.

What happens afterwars is a little bit counter-productive when debugging:
An error in the ControllerMethod is rendered as a template View error.   Not so nice isn’t it ?

Controller methods should Return a View that has all the required parameters to render the View. But if inside that View, you are going around the loop, rendering another Controller that in turn has another View, can be the start of a infinite loop that swallows the universe and you should get a warning red light in your Frontal Lobe. Overcomplicating things with quick and dirty solutions is the wrong way in Software architecture and the responsible of a big amount of relationship problems.

I vouch for strong architecture in software projects

This cheap solutions, like using this render commodities, lead to the start of the bad. And I suggest to avoid it as much as you can unless there is no other possible way.  And certainly there is!

That is the reason to use MVC. To separate Code from Presentation layer, start mixing both, and your architecture will leak.

Symfony Bundles that come always handy for Admin Panels

After a quite accidental start with the Framework I’m enjoying a lot developing stuff with their Form component.
Using bootstrap and almost without any front-end javascript one can build great Admin-dashboard forms, using only a :
{{ form_start(form) }}
{{ form_end(form) }}

Where you want the form to be rendered in the twig template.

As one of my jobs is building friendly Admin Panels, I started to realize that apart of some custom tailored-made solutions, frecuently there is a ground base that works for almost any CMS or CRUD (CReate, Update , Delete manager)

So instead of googling and fetching them one by one, you can find them, or comment them in this post:

  1. TinymceBundle
    Great one.  After installing it, you have a ready made
    {{ tinymce_init() }}
    to put at the end of your twig template. All what you need to do is adjust the config and add a “tinymce” class in your FormTypes.
    Alone with that you can build a CMS in some minutes.
    How cool is that ?
  2. KnpPaginatorBundle
    Whenever we list stuff and becomes large, we need to paginate. This one comes really handy. And like almost all the KNP bundles, is a really nice piece of code, and developer friendly.
  3. Bootstrap-bundle
    Bootstrap is the state of the art front-end to deploy Admin Dashboards.  I had a little fight before making this one work in my Linux dev machine, but is just because I’m not a very front-end guy at the moment, and didn’t had this CSS tools to compile things.  Actually you don’t need this if you want bootstrap base, but I though that having it in a Bundle and thus, being able to install it by composer was a cool thing. And it is!

And that’s basically the 3 things I mostly use all the time.
There are hundreds more, but the basic, ground structur is there.  Making a login / password with FOS User Bundle is also very easy.

In the beginning, the first 2 months or so I was looking towards something that creates an Automatic CRUD manager from a mysql table. After learning more Symfony, I realized that you don’t really need something like that, when it’s quite easy to create your Entities from an existing mysql DB and after that make some Form types and base templates. Cannot get more simplified!
Of course will take some effort, but at the end, you have a custom tailored panel with validation at the top where you can add the customization on top to make your Dashboard more usable.
Hopefully you will make your client happier as well.

Composer lines to add this:

require: {
...
"stfalcon/tinymce-bundle": "dev-master",
"knplabs/knp-paginator-bundle": "dev-master",
"braincrafted/bootstrap-bundle": "~2.0",
"twbs/bootstrap": "3.0.*",
"jquery/jquery":  "2.1.3"
}

Symfony heads up

In the latest 6 months I’ve been quite busy learning Symfony, while I ended up partly in stackoverflow, at the beginning searching for answers to my questions and then when I learned how to solve them giving some answers myself.

Now finally I’m at the point where I can code an admin web panel or CMS completely with the framework. And at the same time, more I learn, I discover how much I don’t know. That’s why next year I’m planning to get certified and invest some time and money going to some workshops.

Matthias Noback, author of the book “1 year with Symfony”, is giving on the beginning of 2015 a special training called Hexagonal Symfony.

If you are interested in his training just sign up in the newsletter to check if he is giving the training near your city. For sure it will be a great heads up in your Symfony work.

Symfony2 Best Practices resume

Today I come across this Best practices in Symfony PDF:
http://symfony.com/doc/download-best-practices-book/

And I though about my own practices and where to apply some of this seen in the Best practices book.

Here is a brief 3 points summary of things I would like to change in my next projects:

  1. Using Constant instead of variables in parameters.yml for those settings that rarely (or never) change
    // src/AppBundle/Entity/Post.php

    namespace AppBundle\Entity;
    class Post {
    const NUM_ITEMS = 10;

    }
    As pointed  in the book, doing so, the benefit is that you can access this constant from almost anywhere in your application. Including your twig templates. This is exactly the part I was not aware of:
    // src/AppBundle/Resources/views/Controller/mytwigtemplate.html.twig

    Displaying the {{ constant (‘NUM_ITEMS’ , post ) }} most recent results.
  2. Keep your controllers Thin

    Symfony follows the philosophy of “thin controllers and fat models”. This means that controllers should hold just the thin layer of glue-code needed to coordinate the different parts of the application. As a rule of thumb, you should follow the 5-10-20 rule, where controllers should only define 5 variablesor less, contain 10 actions or less and include 20 lines of code or less in each action. This isn’t an exact science, but it should help you realize when code should be refactored out of the controller and into a service.

    That’s an easy to remember Rule:
    5   Variables or less
    10 Actions (Calls to services / Forms validation, etc)
    20 Lines of code

    Storing hundred of lines for an Action is always a bad idea specially if you are not the only one working for the project.  And it mostly denotes some bad architectural start, since I can imagine that a controller Action has so many lines has parts that are common and can be reused in another actions. So why not to put all related actions in a service ?

    In this same Chapter, has a best practice that I consider really important, and is in my point of view how an ideal Symfony oriented project should be thought:
    You should aggressively decouple your business logic from the framework while, at the same time, aggressively coupling your controllers and routing to the framework in order to get the
    most out of Symfony

  3. Use eventListeners.
    As an example: Pre and Post Hooks
    If you need to execute some code before or after the execution of your controllers, you can use the EventDispatcher component to set up before/after filters

I find eventListeners one of the most cooles features. They are many use-cases, for example OneUp Uploader bundle uses it to handle File uploads, calling an event listener each time a file is uploaded through Ajax. Like that you can find many real use cases to do this kind of automatic things in the background.

If you like any other interesting part of this Symfony Best practices Book, feel free to join the conversation

Symfony Form EventListeners

Frequently when coding forms, there is a constraint or a field that becomes *required depending on the value of a select field. For this and many more user cases, symfony has the Form Event Listeners that are design specifically for that cases.

So if you want to do get the Request in the form to inject it in some custom Constraint, then this is the incorrect way to do it:

public function buildForm(FormBuilderInterface $builder, array $options) {

$request = Request::createFromGlobals();
$request = $request->request->get('MyBundle');
$type = is_null($request['type']) ? $options['data']->getType() : $request['type'];

$builder->add('myDate', 'datetime', array(
'constraint' => array ( new fieldConstraint (array('type' => $type )) )
);

}

The Symfony approach using Form event listeners looks more like:

</pre>
<pre>    public function onPreSubmit(FormEvent $event)
    {
        $form = $event->getForm();
        $data = $event->getData();
// Note that at this point $data comes from POST
        if ($data['type'] === 'sometype') {
// Then we re-declare the form element adding the constraint (And any other needed stuff)
            $form->add('myDate', 'datetime',
                array(
                    'constraints' => array(
                        new fieldConstraint()
                    )
                )
            );
        }
 }

This looks at least more elegant and readable than trying to access the Request from the formType itself.

And the lesson learnt is:
If you feel that you are trying to access a value in a strange, non straight-forward way, then stop and take some time to research. For sure there is an easier way to do it ;)


Sonata-page Bundle CMS

At this point I was going to make a full stop and try to make a step by step installation, that is easy to configure and also self-understandable. But I come to the point of so much trial and error, apart of learning all the command-line stuff and reading installation procedures, that there is no point in stuffing around with Sonata Admin / Users / Pages Bundles if you don’t have the basics right.

So I will leave the SymfonyBaseAdmin as clean as possible, but anyone that wants to try to install it, will have to mess around and have some patience in order to make it work.

In this latest commit, I left the doctrine Orm settings with auto_mapping: true
That is something the Doctrine purist won’t like it so much, but it let’s you mess around adding/removing Bundles from the Symfony AppKernel.php without breaking the Doctrine:schema:update command line option to update the Tables. Now you can add or remove the sonata-page and sonata-user Bundles without messing with the config.yml every time.

One thing I noted after installing the Page Bundle, is that is quite useless without the User bundle, since is all tied up in the Admin area to work together. So at the end I installed and setted up the User Bundle too. I’m leaving the things separated in the config.yml file, so if you don’t need them simply comment or remove the :

  – { resource: sonata-page.yml }
– { resource: sonata-user.yml }

And their respective lines in the Symfony AppKernel

That said, it’s essential to read the Sonata Users and Pages documentation to play around with this.

After running the composer.phar to get all the required vendors, do not forget to run:

app/console sonata:easy-extends:generate SonataPageBundle –dest=”./src”

app/console sonata:easy-extends:generate SonataUserBundle –dest=”./src”

app/console doctrine:schema:update –force

And last step, generate an Admin user for the administration area:

app/console fos:user:create admin –super-admin

POST-ANNOTATIONS

There is another nifty detail that drove me crazy for some minutes, and is that the way that pages work, require that every time you update something is essential to make a new “snapshot” of the site.
So if you publish a set of pages, there won’t be seen by the router, until going to Site Admin and hitting the Create Snapshot button. That is something that I find quite annoying, but it shouldn’t be so hard to workaround.

After playing for about two days with the Page Bundle I can feel that is a powerful component to build your own pages. In no way is meant to act as a “client ready” CMS, it looks more like a straight “developer” tool, but of course with some heavy customization it will become some interesting addition to any project.

MUSIC
This days, while I keep on with my Sonata self-learning project, I’m hearing quite a lot of cool electronic music.
https://play.spotify.com/artist/7yxi31szvlbwvKq9dYOmFI
Along with some Berlin based independant artists, posting some playlists afterwards…

Crud in 5 minutes per Table using Sonata and Doctrine ORM

Create, read, update and delete is something you need to manage in any Project.

Here is simple formula that works using this simplified version of Sonata Admin and here is the list of steps to achieve a new Crud list per entity:

  1. Design your table structure or pick an existing one
  2. Use Doctrine to create your Entity Classes from the Tables
  3. Add an admin service in Sonata to bring up the Crud functionality

Expanding the points above:

#2 Converting existing mySql tables in Doctrine Entities
After adding your mySql database credentials to app/config.yml, having existing table structures / data, run the following command in the project root:
php app/console doctrine:mapping:import –force yourSymfonyBundle xml

This will generate ORM mapping schema information as xml in the directory Resources/config/doctrine that will be used with the next command to generate the Doctrine entities in the Synfony Entity folder.

This is to create the Tables when you have the entities written:
php app/console doctrine:schema:create

For more information read the documentation regarding Symfony and Doctrine

#3 Adding the Entities in Sonata to enable the Crud functionality

<?php
namespace BaseAdmin\BaseAdminBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class CityAdmin extends Admin
{
    // Fields to be shown on create/edit forms
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('city', 'text', array('label' => 'City'))
            ->add('fmuser')
            ->add('name') //if no type is specified, SonataAdminBundle tries to guess it
        ;
    }

    // Fields to be shown on Filter forms (right)
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('city')
            ->add('fmuser')
        ;
    }

    // Fields to be shown on Datagrid lists
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('city')
            ->add('name')
            ->add('fmuser')
        ;
    }
}

Screenshots:
basicAdmin Entities list

basicAdmin Crud List

 

The code to achieve this is Open source and the repository is located here:

https://github.com/martinberlin/SymfonyBaseAdmin

Symfony Base Admin. New project

At the end of April 2014 I wanted to start testing Symfony taking a base project that was already done in Bonfire/ Codeigniter.

Now the time has come, and I’ve been working with Symfony for about 3 months, so I have more MVC knowledge with the framework. At the same time I was searching for something that was similar as Bonfire to start an easy Admin Panel for some projects. I searched for two weeks but didn’t find anything similar, so no surprise there is no easy panel, you must make your own. And it’s not rocket science, so instead of complaining, let’s do it ;)

With this basic principles in mind:

  • As least components as possible, using Symfony last edition, currently 2.5.* as defined in composer.json
    If we add a new component, is because it’s used somewhere, and it’s commented along with a proper commit in the repository. The goal is that the vendors folder is clean and to to keep the starting codebase to a minimum extent.
  • An easy way to link existing SQL tables to entities, using Doctrine ORM. ( There is no import functionality as in Bonfire )
  • Use the quite well documented Sonata, to make this possible, adding the basic functionality and some examples of how to achieve CRUD functionality.
  • Twitter bootstrap in the admin and if possible also in the front-end, to keep a well designed responsive base design 

Putting this in a Public repository on github so anyone can fork it, modify it and use it for any project.

REPOSITORY:
https://github.com/martinberlin/SymfonyBaseAdmin

OOP Fundamentals

There are many different takes on object oriented programming. I’ve saw this video of “Uncle Bob” latest week and I wanted to write a post about the fundamentals of OOP programming.

http://vimeo.com/64086087

I like the way he explains OOP, interfaces, polymorphism and other related areas of object oriented methodology. So before starting with my post series of Symfony, I wanted to review a couple of basics, and how they are supposed to be used.

The benefits of working using OOP is that the application itself becames minimal, and the modules can be coded in independant pieces, that have a decoupled arquitecture and are independantly deployed, hence repairing a certain part does not brake the others. In Symfony this modules are called bundles. A good programming example, is the Symfony components itself, and another Business Logic example I’ve seen recently with independant Bundles is Elcodi.

HISTORY

The formal programming concept of objects was introduced in the 1960s in Simula 67, a major revision of Simula I, a programming language designed for discrete event simulation, created by Ole-Johan Dahl and Kristen Nygaard of the Norwegian Computing Center in Oslo.  Simula introduced the notion of classes and instances or objects (as well as subclasses, virtual methods, coroutines, and discrete event simulation) as part of an explicit programming paradigm.

DEFINITIONS. THE BIG 3

Encapsulation is the packing of data and functions into a single component. The features of encapsulation are supported using classes.

Inheritance is when an object or class is based on another object or class, using the same implementation or specifying implementation to maintain the same behavior (realizing an interface; inheriting behavior). It is a mechanism for code reuse and to allow independent extensions of the original software via public classes and interfaces. The relationships of objects or classes through inheritance give rise to a hierarchy.

Polymorphism is when source code dependancy is opposed to the source of control.

DOWNLOADABLES

Symfony2 Routing cheat sheet

Symfony2 Forms cheat sheet

Symfony 2. New series of Posts coming !

It’s been quite a while I don’t post anything here.

And there is a good reason: I’m quite busy. My family comes to visit a Berlin, got a new full time job as a developer, and when I come back home I still keep on reading documentation and doing simple code examples, that I do not push anywhere because they are only learning sh!ts so far.

But soon I’m planning to release some stuff and maybe create some new sites with Symfony, that serve a purpose. But no more client work for some time, I just want to arrive home, and do other things as reading books, hearing some music or just hang around with friends. Also it’s about 3 months I’m going to a very cool Salsa class every Tuesday and Sunday. Salsakurs is now Mittlestuffe, not anymore the boring basics :)

One of the most interesting books I read so far, and still re-reading it when I want to apply some stuff is “A Year with Symfony” . A name that honours the labour, since it’s only 3 months I started learning the framework and I still feel that I know only 10% of it.

So I wish you all a good, sunny and entertaining Summer!

 

Desarrollo, Investigación y nuevas Tecnologías. Buenos Aires. Berlin.

Seguir

Recibe cada nueva publicación en tu buzón de correo electrónico.

Únete a otros 514 seguidores