Execute native SQL with Doctrine

We can execute raw SQL queries with Doctrine ORM.

If you already used this awesome library you already know all the features Doctrine supplies us at the time to interact with our database. The DQL (Doctrine Query Language) language is a very powerful and one of the most main feature of Doctrine, but, sometimes we have to face really advanced queries and with DQL it could be a little tricky to do it (in version 2 it will be improved).

If you need to do advanced and complicated queries (or not), Doctrine gives you the ability to execute native/raw SQL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

// we build the query
$query = "select id from tabla";

// gets the connection singleton
$con = Doctrine_Manager::getInstance()->connection();

// executes the query
$st = $con->execute($query);

// retrieves the results
$rs = $st->fetchAll();

// Or if you want the associative results
$rs = $st->fetchAssoc($query);

That’s it.

MVC: Design Pattern

A short description about the Model-View-Controller design pattern.

One of the most known patterns in the web is the MVC (Model-View-Controller) architecture, which is very used in software engineer and it’s composed by 3 layers:

  • The Model is the business logic, which represents the basic information which the application works. To persist that information, apps can use different storage systems such as databases. Although this is not a concern for this layer.
  • The View renders the Model in the browser to allow the user to interact with it. This layer could be extended to support multiple view sub-layers.
  • The Controller responses to the user’s actions and executes the necessary changes in the Model.

mvc

The MVC architecture splits the business logic (Model) and the presentation (View), resulting in a very maintainable code. For instance, if an application should run in both desktop web browser and in mobile browser, we just need to work in different presentations (views) while the controller and the model is shared. The model abstract the business logic, which makes the view and controller independent of the business logic and data access.