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!

 

Neues Projekt: Codeigniter wegen Symfony 2

Ich habe noch 1 Woche Zeit. Die Aufgabe ist, diese kleine MVC Projekt:

https://github.com/martinberlin/onstage

In Codeigniter MVC, nach Symfony 2 MVC framework Weiterentwicklung

Dann Ich freue ich mich sowohl in Bezug auf die Frameworks vergleichen in Hinsicht auf:

  • Geschwindigkeit
  • Struktur und Data Models
  • und wie schwer ist es, eine Admin-Panel zu Entwickeln
    (and how hard is to code an admin panel, in case my german is not so clear)

 

How to add Bonfire to an existing Codeigniter framework project

MISSION: Integrate simple codeigniter project https://github.com/martinberlin/onstage
with bonfire powerfull HMVC modules and administration access.

Step 1

Copy application and bonfire folders into project root.

 

Step 2

Modify existing MY_loader class that will be overridden by Step 1 with your custom functions. In my case, I was using sparks library and the existing codeigniter theme functionality. So I left :

application/core

/* load the MX_Loader class */
require APPPATH.”third_party/MX/Loader.php”;

/* This will be class MY_Loader extends CI_Loader {}  in your Codeigniter project */

class MY_Loader extends MX_Loader {

// And copied here my custom methods.

}

Step 3

Routing and class names:

http:/onstage/public/index.php/event/hamburg/215  (Local test)
Fatal error: Cannot redeclare class Events in C:\xampp\htdocs\onstage\bonfire\libraries\events.php on line 33

Small fail: It seems bonfire already has a class called events. And collides with my own events controller…So I will rename it to something else and change routing accordingly.

So, we update the route:
$route['event/(:any)/(:num)'] = “eventos/lookup/$1/$2″;
And the corresponding file controllers/events.php to eventos.php . This is the beautiful part of MVC. We just changed some files and routing, but the URL call will be exactly the same. This internal changes won’t affect at all any frontend functionality.

Ok and now the latest routing update, this time in the apache virtual host, the codeigniter goes to the root. But the Bonfire default is the public directory.

With this change, so far, almost all old codeigniter project is working like before, with the added plus that now has a Bonfire administration. But we have still some routes to correct.
For example, the old city route is no longer working:

http://onstagekonzerte.de/hamburg/

Drops a 404. But the application/config/routes.php are there :
$route['hamburg'] = “home/hamburg”;
$route['munich']    = “home/munich”;

And the home controller has those methods inside. So I yet have to find those.

UPDATE:

The solution to my path problem was solved in two steps:

a)  First changing the application/config.php and removing the index.php page from the index_page variable:
$config['index_page'] = ”;

b)  Modifying the view paths to css / js external HTML resources, referring to step 2 since bonfire goes to /public as default:

<link rel=”stylesheet” href=”/public/css/alpha_background.css”>  So now new route will be :
<link rel=”stylesheet” href=”css/alpha_background.css”>

After this I had http://onstagekonzerte.de running in the front exactly as before, with the benefit of having a complete bonfire admin in the back-end.

I’ve posted this in the bonfire forum to see if I can get some feedback and also to share with others, since this is a completely open project where all changes will be shared on a github account where anyone can fork, edit, and comment on changes.

onstagekonzert.de project update

OnStage Konzerte

https://github.com/martinberlin/onstage/commits/master 

Apr 12, 2014

  1. Martin

    Adding import route

  2. Martin

    Finished module last.fm import + added spark tools

Tricky Php questions where I failed doing a self test before the PHP Certification

Preparing for the exam in a few hours. There are many functions I never used used in the latest 6 years, and that’s all fine, since PHP is quite a bloated language. So I never had the need to use things as mysql_real_escape_shit :)

Or ucword ? WTF is that ? Anyways now learning the latest tidbits, and so far got 41 questions right from 70 which is a lame 5,5 and for sure won’t get approved if I rush on to get it done on time. So I will take it slowly.

#1 Which of the following is a valid way to pass the $callback parameter expected by array_walk()? 

1) An anonymous function
2) An array containing an instantiated object as the first element, and
the method name as the second element
3) A string containing the function name
This question is about callbacks – only these three items in the list are valid ways to specify a callback

I will make a short example of the #2:

<!–?php

class myobj{

   static function test($v){
     echo $v;
   }
}

$arr=array(1,2,3,4);

array_walk($arr,array(“myobj”,”test”));

 

// This is the right way to pass the object and the method that will be executed per array item.

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj, ‘myCallbackMethod’));

more types in the php docs.

// Method is called statically so it should be declared that way or you get a warning.

#2 Right way to parse a web page at http://onstagekonzerte.de as XML?

DOMDocument::loadHTML(file_get_contents(‘http://onstagekonzerte.de&#8217;));

 

#3 A brief explanation about bitwise operators

$b= 4<< 2 + 2;

First of all, via operator precedence 2+2 is executed first resulting in:

$b= 4<< 4;

<< left shit, means that it's multiplied 2 ala n, so in this case: 4 *2*2*2*2 = 64

>> right shift would mean divide, so :  64 >> 4 = 4

#4 The standard PDO fetch by default

Does it return an:
  • Associative Array
  • Numeric Array
  • or Both ?

Leave your answer in the comments :)

Another questions about PDO query, ask about what it performs. Query in PDO does two things:
prepare() and execute(). Only that! Don’t be tempted to add a fetch, that you do afterwards, lazy programmer.

#5 The PCRE tricky question

$pattern= ‘/[a-z]{4} /';

$string = ‘Mary was a little bitch';

$matches = preg_match( $pattern, $string );

print_r($matches);
~

There is always some tricky question like this. So what returns this ?

A 1.    Not the matches, to get those $matches should be added in as a third parameter.  But in this way, preg_match just returns true if the match is found, which in this case would be ‘ttle ‘ since bitch won’t do it since it’s missing a space at the end. Bitchy, doesn’t it ?

#5b The PCRE tricky question in bitch mode

$pattern= ‘# \w*?[aeiou]{2}\w*? #';

$string = “There’s a lion loose in the Maister park”;

$matches= array();

preg_match_all($pattern, $string, $matches);

First of all, the # delimiters are valid delimiters, the only requirement is that whatever you pick to match as the start should be matched at the end.  Note that as ” lion ” is matched, eats the space in “loose ” so loose will NOT match. And there you may be trapped.

There’s a lion loose in the Maister park
Array (
[0] => Array (
[0] => lion
[1] => Maister
)
)

#6 The HTTP status questions

Everybody and his mum, know about 404 not found.  But in this exam there come another statuses as:

  • 401  – Not authorised, put your user and password in this little box
  • 400 - Bad Request
  • 403 – Forbidden
  • 408 – Request Timeout

#7 The PHP magic methods

Remember the magic list:

  • __construct
  • __destruct
  • __call
  • __callStatic
  • __get
  • __set
  • __isset
  • __unset
  • __sleep
  • __wakeup
  • __toString
  • __invoke
  • __set_state
  • __clone       Some questions may ask what magic methods is instanced when you clone a class. Well it’s pretty obvious, don’t get lost there, is this one.

Analog B&W scan done today:
Image

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 498 seguidores