Symfony – starting up with Symfony

I’ve recently been learning a lot of Symfony in my attempt to make the transition from home-made MVC frameworks to a full-featured OO PHP MVC framework. Everything that follows is my personal view on Symfony and a way to clarify things in my head. I’m just starting out with Symfony, so I’m definitely NOT an expert. All articles refer to “symfony 1.4″.

Who can use this / What is OOP / What is MVC

You should be familiar with the concepts of OOP. There’s a lot of documentation out there, I can’t go into it here. OOP (Object Oriented Programming) makes you think about you application in a different way. Instead of using global functions which have no knowledge of eachother and calling them wherever needed, you first define the logic of you application based on actual entities (or objects). A simple example should clarify things a bit:

Selecting products from the database and listing them and some of their attributes
Non OOP:
-> SQL: “SELECT * FROM products WHERE is_active=’1′ LIMIT 10″
-> Database connection (usually manual)
-> Retrieve results and populate an array ($results)
-> Foreach row in array, create a visual presentation and list properties
(if ($product[is_active'] == ’1′) { echo $product['title']; echo $product['description']; }, etc)
You usually do database connection, processing of results and displaying results in one file, all mixed up.

OOP:
-> You define the logic of you application and you might create an object of type Product with predefined properties and methods
(properties could be: title, description, is_active / methods could be: getTitle(), setTitle(), getDescription(), isActive(), hasChildren(), etc)
-> For SQL and Database connection you use a dedicated class or object-mapper
-> The database query returns an array of already known objects, in our case Products
-> You might display data like this: if (Product->isActive()) { echo Product->getTitle() }
You will most likely use separated files for the Product object, database mapper, html presentation.

If you already work with objects in PHP and you separate your data processing from your presentation a little bit, you could benefit from using a framework.
The way I used to do it, I would use a central wrapper file main.php that includes PHP required classes, HTML headers, ‘processing’ of data and ‘presentation’ of data, plus navigation, footer, etc.
Then, a call to a product listing page would go through main.php and include 2 files: products_p.php (processing) and products_c.php (content) (not really the best choice of filenames). But the products_p file would connect to database, retrieve products, handle fatal errors and prepare data for the content.
The content (in products_c.php) would check if the results existed and if so, list the results using HTML and PHP.
This simple aproach works for many projects. Problems arise when you need more complex stuff like searching, paging results, securing everything and extending it down the line. This is where MVC frameworks come in.

MVC Frameworks

MVC stands for Model View Controller. There’s also a lot on the web about MVC and I can’t go into details. But it’s all bout the separation we talked about
The Model is where you define you objects
You know your application wil use objects like Product, Category, User, Cart, Order. A lot of work needs to be put into planning at this stage. Think of the objects in your application more like ‘real’ objects instead of abstract concepts. A Product has a name, a description, a price, a category, etc.
The Controller basically links the Model to the View. It’s the ‘processing’ part. When a request is made, that’s an event that triggers actions. In the end, the results of those actions will be used to create the View.
The View is the presentation layer, it’s usually a HTML template into which you insert dynamic pieces of code. You might call them ‘snippets’, ‘includes’, ‘slots’, ‘components’ or whatever. Basic components could be the title of the page or the content. You don’t check things in the view, you don’t ‘process’ results, you don’t request new objects. You just display what’s been handed to you from the Controller.

Symfony pros and cons

Symfony is really cool. I’ll list my first impressions as I recall them as Pros and Cons.

Pros:
Starting a new complex project is easy (if you’ve spent time planning your objects and database schema)
The backend admin interface is really easy and cool to create.
You don’t worry that much about security and attacks and injection and what-not. Symfony pretty much takes care of that.
Forms are secure, they include validation and error handling.
You get a cool ORM (object relational mapper) for linking the objects to the database
You get caching, logging and url handling by default
The documentation is out there.

Cons:
There is a learning curve. At first everything seems unnecessarily complex and the directory structure is pretty scary.
Even though it’s extremely easy to start up and create the complex hierarchy of a project, customizing certain parts soon becomes difficult.
Forms in symfony are actually evil, you realize that soon enough…
The documentation is out there but… it’s a huge project. You need to read A LOT while learning. The project seems to be quite active and you have to filter out results for older versions (1.0 and 1.2). The documentation also lacks in some aspects. Symfony 2.0 is coming soon. Excited about that :)

What you should know about Symfony if you’re just starting up

You develop on your local machine

That means you have to install and configure LAMP, MAMP, XAMPP or whatever AMP you like. Basically Apache, MySQL, PHP. I use a Mac, I went with XAMPP. Installation and configuration was NOT smooth and easy. (I had problems with setting up Apache’s Virtual Hosts, I had to do some overriding of CLI PHP to get rid of some MySQL PDO errors, etc)
You work in a ‘development’ environment and, once everything is ready, you deploy the stuff to the production server, in ‘production’ mode.

You need a good editor

I’m not really familiar with the terminology, but you basically need an IDE that supports autocomplete and that detects dependency between objects. A simple text editor in not enough in my opinion, I love Coda but it won’t cut it for Symfony, TextMate was not enough, BBEdit was nicer but Eclipse won my heart (even though I hate Java…)
It’s the first time I develop fully in Eclipse, and everything seems ok. You’ll need to install PDT for Symfony and maybe the YAML Editor. Search the web for how to do that. I think it’s not possible to weed out all the errors inside Symfony itself, so you’ll either have to do a lot of web searching or just ignore the few hundred errors. (it’s my understanding the eclipse parses code it shouldn’t be parsing or that symfony doesn’t explicitly exclude certain files from parsing…)

The structure of your project

There’s the symfony core and configuration files and then there’s applications. Traditionally, applications are ‘frontend’ and ‘backend’. Inside the applications, you get a lot of stuff, including modules. I’m not really sure how to define a module. It’s a part of you application, could be a page, could be directly tied to an object in your model, could be a set of connected actions. You will usually have a User module in you application, a Product module, etc.
Inside modules, you separate the controller from the view (or actions from templates).
So, a typical project would look like this

onlinestore
|_ config (configuration files, global, database settings and schema)
|_ lib (contains the model object classes, forms, etc)
|_ apps
   |_ frontend
       |_ config (configuration specific to this app, including url handling)
       |_ modules
           |_ product (an example module, also contains a lib (model) and template (global view))
               |_ actions (this is the controller layer)
               |_ templates (view templates)

There’s a lot more, like ‘cache’, ‘log’, ‘plugins’ and the public ‘web’ directory. These are pretty self-explanatory.

Creating the base of a new large application is easy. If you know what you’re doing and you’ve planned you objects and database schema well, then creating the basic backend admin interface for instance takes like 5 minutes. The first impression I got when doing that (took me more that 5 minutes) was ‘Wow!’. It looks good, it works out of the box, you get you basic CRUD actions (Create, Retrieve, Update, Delete) all ready and working. Impressive.

How a Symfony project works

An easy way to look at it is:

1. You enter a url to your project;
2. Symfony searches the url routing tables (like .htaccess but better, I think) and chooses the right module and action
3. Once inside the module, the action retrieves needed objects from database, processes them, and prepares them for the view
4. The module’s designated view template include the results of the action
5. The module’s template is included into the master template that’s displayed in the browser.

Where does Symfony really help?

It helps you start you project imediatelly. Imagine you’ve layed out the basic structure of your project, you know what objects you’ll use, you’ve defined the database schmea, you know the relations between objects. This is all on you and this comes from experience. Symfony helps you with the next step:

It takes your objects and your database schema and automatically creates all object classes, database tables, dependencies and forms for you. That’s what the complex structure of folders is for. One more step and you also have all CRUD operations at you fingertips. Another step and you can easily populate your database with sample data. It simplifies immensely the creation of the admin interface. So, at this point you kind of have a website.

Once you get your nose into the actions and the templates, you realize pretty quickly how it all works and creating lists of objects or pages of object details is very easy. Symfony takes that initial huge amount of work and makes it easy and smooth.

Next, it’s on you to customize everything. And it’s a lot of work.

Customizing

You quickly realize you need user authentication and registration for your website. Luckily there’s a plugin for that. Not everything is straightforward and you always feel like everything is ‘under development’ but it works. (sfDoctrineGuardPlugin)
Soon enough you realize your forms are more complex than you thought. You need image upload, resize and thumbnail creation capabilities. There’s a plugin for that too (sfThumbnailPlugin). You soon want jQuery in you project (sfJqueryReloadedPlugin) (I never got it to work though), extra form elements like calendars and date pickers, sliders, captcha and whatever (sfFormExtraPlugin). There are plugins out there for most of these but implementing them is not always easy. The community seems to be large and continually developing though.

Forms are a separate chapter as Symfony employs an interesting workflow to ensure user submitted data is cleaned, validated and then saved. But it’s complex and cumbersome. The good news is that everything can be extended and modified, the bad news is that you need to learn a lot to do it.

As I progress with my Symfony project I’ll post more here. Criticism is welcome, especially if it’s about best practices in Symfony.

This is a work in progress, I’ll eventually put the articles in order. For now, you can also check out:
Symfony – forms in Symfony

Tags:

One Response to “Symfony – starting up with Symfony”

  1. Here is the link to very good free PHP IDE with special Symfony plug-in: http://codelobster.com/symfony.html

Leave a Reply