Archive for the ‘symfony’Category

PHP conferences update

There are some great conferences around the PHP world that are coming up or are being announced. Here is the list (if we missed one, please let us know)

  • Open Source India – September 19-21, 2010 – Chennai, India
  • PHP Matsuri – October 2-3, 2010 – Tokyo, Japan
  • Symfony Day Cologne 2010 – October 8, 2010 – Cologne, Germany
  • ZendCon – November 1-4, 2010, Santa Clara, California
  • Symfony Live San Francisco – February 2011, San Francisco, California
  • Symfony Live Paris – March 3-5, 2011 – Paris, France



As always, if you work around PHP, we encourage you to participate of conferences which are an invaluable tool to enhance your skills and meet with fellow developers and colleagues.

31

08 2010

Symfony + Git + Capistrano = Capifony

Introduction

Deploying applications to production/live servers is always a delicate task. The whole process needs to be quick to minimize downtime. Automating the deployment process helps running repetitive tasks minimizing the possibility human error. It is also a good idea to have a proven and easy way to rollback to a previous version if something goes wrong.

Capistrano and more specifically Capifony can help with the automatic deployment of symfony projects.

What is Capistrano?

Capistrano is a time saving command line tool, written in Ruby, that helps you execute automated tasks on remote servers from your local environment. It also allows you to run symfony commands. Capistrano was built to help you administer all your servers from one place, running commands, installing software and keeping everything in sync. Oh… and of course it has a rollback mechanism.

It’s one of those tools Ruby developers have that we often wish we had in symfony, and now we do. Enter Capifony…

Capistrano commands

Capistrano has 2 base commands:

1. `capify …`;
2. `cap …`.

Capify will create 2 files in a specified path (1st argument of `capify`):

1. `Capfile` – capistrano loader. It loads all basic libraries & project config file;
2. `config/deploy.rb` – project config file. Your configs & variables setup for project placed here.

The second command, `cap`, actually runs capistrano tasks on the remote server with config from your `config/deploy.rb`.

A capistrano recipe is a package of tasks, grouped into namespaces. You can use embedded tasks or write your own (place them in your `config/deploy.rb`). Once a task is written you can run it with `cap` command under your project directory:

cap namespace:task

Deployment recipe
—————–

As mentioned above, Capistrano is typically used to deploy Ruby On Rails applications. How does it work? Basically, capistrano must know 4 things:

1. addresses of your web, app & db servers (most often it’s the same address);
2. address of your source code control system repository (if you have one).

Keep in mind, that capistrano uses SSH to run remote tasks so you will need to have shell access to all your remote servers.

During the deploment process, Capistrano will maintain different files & directories on server. It will create a `releases` directory that has dated directories with the actual copy of your code for each release. In addition, Capistrano symlinks your shared folders (common between releases) into release directories, so logs, assets & other files keeps the same between deployments.

What is Capifony?

Capifony is a new RubyGem package, that extends Capistrano functionality so it can work with symfony PHP projects. In essence it’s a package of custom and extended original capistrano recipes.

Demo project

To fully understand how capifony works and what it does we need to create one simple symfony application and deploy it to our test server.

Step 1: Install

I assume that you already have Ruby & RubyGems installed on your local environment (MacOS X has this out of the box – simply update gems with `sudo gem update –system`).

To install capifony and capistrano, simply run:

gem install capifony

This command will install capifony and it’s dependencies (capistrano for example) to your local host. NOTE: Your local host is the only place where you need to install capifony & capistrano.

It’s also good practice to create and copy the SSH key to speed up the connections to your remote repositories.

Generate key with:

ssh-keygen -t rsa

Next, copy your public key to remote server that you want to connect to (I am going to assume your SSH user is called `demoUser`):

cat .ssh/id_rsa.pub | ssh demoUser@your.domain.com "cat >> .ssh/authorized_keys2"

Then just try to connect with:

ssh demoUser@your.domain.com

If all goes well the remote server will just let you in without password prompt.

We then need to create the project repository on server, so let’s create one:

ssh demoUser@your.domain.com
sudo mkdir /var/repos
sudo chown demoUser !$
cd !$
mkdir demo.git
cd !$
git --bare init

Step 2: Symfony project setup

Lets create empty git repository for our new demo site (we will use git as SCM, but you can use subversion or any other source code manager that’s supported by capistrano):

cd /var/www
mkdir demo
cd !$
git init
touch .gitignore

Now add these lines to your `.gitignore` to exclude asset symlinks, databases config, cache, backups, uploads & log folders from our git repository:

web/sf*
web/uploads/*
cache/*
plugins/.*
log/*
config/databases.yml
mkmf.log
.rsync*
backups/*

It’s time to add `.gitignore` to stage and make our initial commit:

git add .gitignore
git commit -m 'initial commit'

Finally we can generate skeleton for our demo project and commit it:

symfony generate:project demo
git add .
git commit -m 'symfony project created'

Now lets add the database schema to `config/doctrine/schema.yml`:

	---
	Topic:
	  actAs:
	    Timestampable:    ~
	  columns:
	    id:
	      type:           integer(4)
	      primary:        true
	      autoincrement:  true
	    title:
	      type:           string(256)
	      notnull:        true
	    content:
	      type:           clob
	      notnull:        true

And add some fixtures into `data/fixtures/fixtures.yml`:

	Topic:
	  topic1:
	    title:    First topic
	    content:  first topic content
	  topic2:
	    title:    Second topic
	    content:  second topic content
	  topic3:
	    title:    Third topic
	    content:  third topic content

Build database and model files:

symfony doctrine:build --all --and-load --no-confirmation

And you need to generate the `frontend` application and put `main` module in it:

symfony generate:app frontend
symfony generate:module !$ main

To make this more interesting let’s put some logic for our application. Go to `apps/frontend/modules/main/actions/actions.class.php` and replace the `executeIndex` function code with this:

/**
* Executes index action
*
* @param sfRequest $request A request object
*/
public function executeIndex(sfWebRequest $request)
{
   $this->topics = Doctrine::getTable('Topic')->findAll();
}

And the view. Go to `apps/frontend/modules/main/templates/indexSuccess.php` and add:

<dl>
  <?php foreach ($topics as $topic): ?>
    <dt><?php echo $topic->getTitle() ?></dt>
    <dd>
        <?php echo $topic->getContent() ?>
    </dd>
  <?php endforeach; ?>
</dl>

Now if you open http://your.local.demo.host/frontend_dev.php/main in browser you will se definition list with our 3 topics.

Add changes to git:

git add .
git commit -m 'finished project'

Stage 3: symfony library with project

It’s good practice to include the dependent version of symfony in your project repository. You can do this in two ways:

1. Simply copy symfony library under `lib/vendor/symfony` directory & commit it;

or

2. Submodule symfony library from another repository.

I like second way. To do this, we will submodule Vincent Jousse’s symfony 1.4 git mirror:

git submodule add http://github.com/vjousse/symfony-1.4.git lib/vendor/symfony

Don’t forget to fix symfony path in `config/ProjectConfiguration.class.php` (after both ways) from:

require_once '/opt/local/lib/php/symfony14/lib/autoload/sfCoreAutoload.class.php';

to

require_once dirname(__FILE__) . '/../lib/vendor/symfony/lib/autoload/sfCoreAutoload.class.php';

And commit this:

git add .
git commit -m 'bundled symfony'

Step 4: Push local project to remote git repository

Remember our `demo.git` repository on `demoUser@your.domain.com` that we’ve created earlier? It’s time to push our project to it:

git remote add origin 	ssh://demoUser@your.domain.com/var/repos/demo.git
git push origin master:refs/heads/master

Now your project is pushed to remote repository, where anyone who has SSH access can push/pull it. Also, we will use this repository to deploy new versions with capistrano.

Step 5: Config

Now is the time to play with capifony itself. First of all, lets “capifony” our project:

capifony .

Capifony created `Capfile` and `config/deploy.rb`. Go into `config/deploy.rb` and edit it’s variables. To set capistrano config variables, you need to call `set :var_name, “var_value”` instruction inside `deploy.rb`. Below is the list of main variables:

* `:application` – set your application name here (“demo” in our case);

* `:domain` – domain of our remote server. This variable will be auto-populated with `#{application}.com` (demo.com in our case). Place your server address here if it’s not `demo.com`. I set it to `#{application}.everzet.com`, because my test host is http://demo.everzet.com;

* `:deploy_to` – path, where we will deploy our application (in most cases `/var/www/#{domain}`);

* `:repository` – path to repository (`#{domain}:/var/repos/#{application}.git` in our case);

* `:scm` – source code management tool. In our case set it to `:git`, but it can be any of `accurev`, `bzr`, `cvs`, `darcs`, `subversion`, `mercurial`, `perforce`, `subversion` or even `none`;

* `:use_sudo` – set to `false`, because we doesn’t need sudo during our deployment process;

* `:deploy_via` – set it to `:remote_cache`, so deployments will last less time;

* `:git_enable_submodules` – set it to `1` if you have submodules in project (if you staged symfony as submodule for example);

Also add this line to `config/deploy.rb`:

ssh_options[:forward_agent] = true

if you want to use your local SSH key instead of remote one for git checkout.

Your resulting `config/deploy.rb` is must be something like this:

set  :application,            "demo"
set  :domain,                 "#{application}.everzet.com"
set  :deploy_to,              "/var/www/#{domain}"

set  :scm,                    :git
set  :git_enable_submodules,  1
set  :repository,             "#{domain}:/var/repos/#{application}.git"
set  :deploy_via,             :remote_cache

role :web,                    domain
role :app,                    domain
role :db,                     domain, :primary => true

set  :use_sudo,               false
set  :keep_releases,          3
ssh_options[:forward_agent] = true

Step 6: Deployment

To start, we need to know 3 basic capistrano commands:

1. `cap deploy:setup` – create directories on server;
2. `cap deploy:cold` – copy code, build database, make symlinks;
3. `cap deploy` – copy code, make symlinks.

Now run:

cap deploy:setup

This command will create the following folder structure on your server:

	`-- /var/www/demo.everzet.com
	  |-- releases
	  `-- shared
	    |-- log
	    `-- web
	      `-- uploads

After few deployments, folder structure will eventually become something like this:

	`-- /var/www/demo.everzet.com
	  |-- current (symlink)
	  |-- releases
	    |-- 20100512131539
	    |-- 20100509150741
	    `-- 20100509145325
	  `-- shared
	    |-- log
	    |-- config
	      `-- databases.yml
	    `-- web
	      `-- uploads

What does all this mean?

1. `releases` is folder, where all your releases sits. Every release is a timestamped folder under `releases` directory.

2. Every release has symlink to shared files and folders, placed in `shared` directory. This files & folders stays same between deploys;

3. capistrano creates symlink to latest release, called `current`. This is your current project folder to work with (where to point web servers, crontabs etc.).

Now lets deploy our application for the first time:

cap deploy:cold

If you’ve configured your remote server hosts right, you now can open http://your.remote.host/main & see you symfony application there.

Step 7: Deploy & Rollback

Now what if we change something, deployed it and it’s broke our site? Lets break something!

Open `apps/frontend/modules/main/actions/actions.class.php` and change

$this->topics = Doctrine::getTable('Topic')->findAll();

to

$this->topics = Doctrine::getTable('TopicS')->findAll();

Save it, commit it and push to remote repository:

git add .
git commit -m 'buggy change'
git push origin master

Now deploy this bug:

cap deploy

and try to open http://your.remote.host/main. Oh, no! Something broke. What to do? Simple! Run:

cap deploy:rollback

and capistrano will roll your server back to previous working version of project and you will be able to find, fix, push and deploy the bugfix later, without problems.

Conclusion

Capistrano is mighty tool that has served RoR developers for many years. Now the symfony world can use these best practices in their development workflow. It’s as simple as installing capifony gem.

If you want to add/request something or read further manuals – please, visit project repository on github.


About the Author

Konstantin Kudryashov (aka everzet) is a web developer from Minsk, Belarus. Most of the time, he builds symfony applications. When he’s not – he maintains symfony bundles for TextMate, writes symfony plugins & php libraries.

12

07 2010

symfony 1.3.6 and 1.4.6 security release available at ServerGrove

New versions of symfony framework have been released today. The 1.3.6 and 1.4.6 releases include a security vulnerability patch, check out the blog post announcing the release for more details. We recommend all our customers (and non-customers as well) to update their projects with the latest releases.

As always, all these new versions are already available on all our servers. If you are a VPS customer, make sure to update your local library to get the latest and greatest. And happy symfony coding!

29

06 2010

Jornadas de symfony, can you think of a better way to spend your day?

Another great symfony conference is happening this July, “Jornadas de symfony”, and might we add, it’s our favorite type of day. The free conference will last two days and takes place at the Castellon University near Valencia, and is limited to 170 people. The lineup looks fantastic.

Day 1 (July 5th, Monday):

  • 09:45 – 10:00 Welcome
  • 10:00 – 10:50 Introduction to symfony (Alfonso Alba, nerium.es)
  • 11:05 – 11:55 The ORM Doctrine (Nacho Martín, makoondi.com)
  • 12:10 – 13:00 Taming symfony views (José Antonio Pío, acilia.es)
  • 13:00 – 15:00 Lunch
  • 15:00 – 15:50 Admin generator, with great power comes great responsibility (Javier López, flai.es)
  • 16:05 – 16:55 Architecture and design of development environment (Ricardo Borillo,xml-utils.com)
  • 17:10 – 18:00 Symfony in Spain. Case study I: voota.es (Sergio Viteri, voota.es)
  • 18:15 – 19:00 Symfony in Spain. Case Study II: Using Symfony in the management of an advanced computer center (César Suárez, ceta-ciemat.es)

Day 2 (July 6th, Tuesday):

  • 9:00 – 09:50 Taming forms: sfForm (José Antonio Pío, acilia.es)
  • 10:05 – 10:55 Plugins, don’t reinvent the wheel (Jordi Llonch, laigu.net)
  • 10:55 – 11:30 Rest
  • 11:30 – 12:20 MongoDB and symfony (Pablo Díez, pablodip.com)
  • 12:35 – 13:25 Symfony, cloud computing and the scalable web (Asier Marqués, blackslot.com)
  • 13:40 – 14:30 Symfony 2 (Javier Eguíluz, symfony.es)

Networking: Between talks there will be time to network, chat and catch up.

These presentations will be in Spanish only.

It is amazing to see conferences like these popping up around the globe. They are infinitely important to help the betterment of symfony and the education of the community. We will continue to try to support as many of these as we can and commend the Symfony de Charlas crew for putting together such a well rounded event. We hope this is one of many symfony events to start around the globe.

More information at: http://decharlas.uji.es/symfony/

03

06 2010

symfony 1.3.5 and 1.4.5 released and available at ServerGrove

New versions of symfony framework have been released today. The 1.3.5 and 1.4.5 releases include a security vulnerability patch, updated dependencies of Propel and Lime, and a few bug fixes. Check out the blog post announcing the release for more details. We recommend all our customers (and non-customers as well) to update their projects with the latest releases.

Since we are talking about symfony, it is worthy to mention the announcement of a Symfony Live Online Conference which will cover updates on Symfony 2. The ticket to join the conference is only 20 euro (early bird pricing) or 30 euro, so there is no excuse to be part of this if symfony is your thing.

And one last note, as always, all these new versions are already available on all our servers. If you are a VPS customer, make sure to update your local library to get the latest and greatest. And happy symfony coding!

Tags:

02

06 2010

PHP 5.3 on shared hosting

We are pleased to announce that we are now offering PHP 5.3 for shared hosting as well the 5.2 version. We have been supporting 5.3 on our VPS accounts and it has proven to be reliable and stable so now when you sign up for shared hosting you can pick which version of PHP you want. Pricing for hosting with PHP 5.3 is the same as the other versions. While some PHP Hosting companies are offering PHP 5.3, many are offering it as a CGI, we tested this option and due to performance reasons we decided to dedicate a whole server to PHP 5.3. The downside is that you can’t run 5.2 and 5.3 on the same machine, the upside is that it’s freaking faster this way. Current ServerGrove customers can migrate to PHP 5.3 free of charge. Just give support a shout and request that your hosting account be migrated to a 5.3 server.

PHP 5.3 has a number of new features released, including:

and more. The full list can be viewed here http://php.net/releases/5_3_0.php

PHP 5.3 is specially good for sites and applications developed with frameworks like symfony and Zend Framework, as they run much faster thanks to the improved memory management. Additionally, the new branches PHP frameworks like Symfony 2, Lithium and Zend Framework 2.0 will only run on PHP 5.3 and above.

Please keep in mind that some PHP scripts and applications that were developed on older versions of PHP may not run with PHP 5.3, so it is always a good idea to test and make sure everything works correctly.

13

05 2010

MongoDB with PHP and symfony

Introduction

There has been a lot of talk about document databases and how applicable they are for Web 2.0 application development. There are a bunch of projects in the “NoSQL” realm that are making a lot of noise, CouchDB, Cassandra, and MongoDB are the ones that are most mentioned. MongoDB is a scalable document database, which is also open source.

Part of our business is to develop internal applications and  support customers, so we dedicate a good amount of time to research, test and learn new technologies. We have been following this whole movement and decided to give MongoDB a try.

What has really taken our attention regarding MongoDB is its simplicity, yet how powerful it is. It lowers the barrier to develop DB-driven applications even more.

In MongoDB there are no tables and rows. You have collections and documents instead. And collections can contain any type of document, it is not limited by the columns or fields like a table. In some scenarios, this is a really big plus. Yet, some people, mostly those born and raised with RDBMS will be scared to death due to the lack of schema and rigid structures. As always, if you plan ahead and do your homework and design your entities properly, you will be fine.

Since collections can have different types of documents, let’s say, an array, you can update the document with more fields in the array. In the RDBM world to do this, you have to change your schema, making application upgrades one of the biggest pains.

Using MongoDB and PHP

To get started with MongoDB and PHP, you need to download and install the server. From the website you can download packages for your preferred OS or you can download the source and compile it. Installation is really simple. Once you have the files in your computer, to start the server all you have to do is run the daemon, ie.:

# /usr/local/mongodb/bin/mongod

MongoDB will start and initialize its DB storage.

Now you can connect with the mongo command line client or other clients like MongoHub, PHPMOAdmin among others.

To connect to MongoDB from PHP, you will need to install the mongo pecl extension. On Mac OS X or Linux, run:

# pecl install mongo

Then add the following line to php.ini and restart your web server:

extension=mongo.so

The PHP.net site has a very good tutorial on how to get started with MongoDB and PHP. Basically, to store something in MongoDB you follow these simple steps:

// connect to the default DB server, localhost
$connection = new Mongo(); 

// select a DB
$db = $connection->dbname;

// get a collection, if it does not exist, it will get created
$collection = $db->users;

// insert a document
$collection->insert( $doc );

That’s it! No table creation, nice! For more information on how to retrieve data, go to the PHP.net tutorial.
MongoDB stores data in a binary JSON format. If you are familiar with JavaScript, you will know JSON. When you store a PHP object, when it is time to get the data from the DB, you will get an array instead. For many uses, this is OK, but some times, for more complex solutions, objects are necessary. Fortunately there is a solution already!

Enter ODM (Object Document Mapper)

ODM is a new project created by Jon Wage, a core developer of the popular Doctrine ORM. The Doctrine\ODM namespace will be the home to PHP 5.3 object mappers for Document based storage systems like MongoDB. Currently only the Doctrine\ODM\MongoDB code has been implemented and it will map PHP objects with MongoDB documents. So when you store PHP objects in MongoDB and you need to retrieve them, you will get back PHP objects. Not only that, but it also helps with relations between objects. The project home page includes a basic usage manual and a full working example.

What’s really nice about this solution is how unintrusive it is. Your classes are pure PHP classes without having to extend other classes. The only requirement is that you map your properties using one of the support metadata drivers. In this example we use the AnnotationDriver:

namespace Entities;

/** @Entity */
class User
{
    /** @Field */
    private $id;

    /** @Field */
    private $username;

    /** @Field */
    private $password;

    /** @Field(embedded="true", targetEntity="Entities\Phonenumber", type="many", cascadeDelete="true") */
    private $phonenumbers = array();

    /** @Field(embedded="true", targetEntity="Entities\Address", type="many") */
    private $addresses = array();

    /** @Field(reference="true", targetEntity="Entities\Profile", type="one") */
    private $profile;

    /** @Field(reference="true", targetEntity="Entities\Account", cascadeDelete="true") */
    private $account;

    public function getId()
    {
        return $this->id;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function setUsername($username)
    {
        $this->username = $username;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function setPassword($password)
    {
        $this->password = md5($password);
    }

    public function getAddresses()
    {
        return $this->addresses;
    }

    public function addAddress(Address $address)
    {
        $this->addresses[] = $address;
    }

    public function setProfile(Profile $profile)
    {
        $this->profile = $profile;
    }

    public function getProfile()
    {
        return $this->profile;
    }

    public function setAccount(Account $account)
    {
        $this->account = $account;
    }

    public function getAccount()
    {
        return $this->account;
    }

    public function getPhonenumbers()
    {
        return $this->phonenumbers;
    }

    public function addPhonenumber(Phonenumber $phonenumber)
    {
        $this->phonenumbers[] = $phonenumber;
    }
}

Take a look at the DocBlocks and how we map the properties to the document.

Once you defined your entities, the usage is super simple:

require '/path/to/doctrine/lib/Doctrine/Common/ClassLoader.php';

use Doctrine\Common\ClassLoader,
      Doctrine\Common\Annotations\AnnotationReader,
      Doctrine\ODM\MongoDB\Mongo,
      Doctrine\ODM\MongoDB\Configuration,
      Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver,
      Doctrine\ODM\MongoDB\Mapping\Driver\YamlDriver,
      Doctrine\ODM\MongoDB\EntityManager;

$classLoader = new ClassLoader('Doctrine\ODM', __DIR__ . '/../lib');
$classLoader->register();

$classLoader = new ClassLoader('Doctrine', '/path/to/doctrine/lib');
$classLoader->register();

$classLoader = new ClassLoader('Entities', __DIR__);
$classLoader->register();

$config = new Configuration();

$reader = new AnnotationReader();
$reader->setDefaultAnnotationNamespace('Doctrine\ODM\MongoDB\Mapping\Driver\\');
$config->setMetadataDriverImpl(new AnnotationDriver($reader, __DIR__ . '/Entities'));

$em = EntityManager::create(new Mongo(), $config);

$user = new User();
$user->username = 'jwage';
$user->password = 'changeme';

$user->profile = new Profile();
$user->profile->firstName = 'Jonathan';
$user->profile->lastName = 'Wage';

$user->account = new Account();
$user->account->name = 'Test Account';

$em->persist($user);
$em->flush();

For more information, visit the project home page. Please note that this project is in very early stages of development, so things may change.

MongoDB, ODM and symfony

We will demonstrate how to use MongoDB with ODM and symfony. Symfony 2 is still in alpha stage, so even though it would be a perfect fit with ODM, we will stick with symfony 1.4 for now. For this part of the article, you will need to know a little bit of symfony.

1. If you don’t have a symfony project, go ahead and create it with ./symfony generate:project myproject

2. Download Doctrine2 (you will need the new class autoloader) and ODM into myproject/lib/vendor

3. Add the class auotoloader to the config/ProjectConfiguration.class.php file:

require_once __DIR__.'/../lib/vendor/symfony/lib/autoload/sfCoreAutoload.class.php';
sfCoreAutoload::register();

require __DIR__.'/../lib/vendor/doctrine2/lib/Doctrine/Common/ClassLoader.php';

use Doctrine\Common\ClassLoader, Doctrine\ODM\MongoDB\EntityManager;

class ProjectConfiguration extends sfProjectConfiguration
{
  public function setup()
  {
    $classLoader = new ClassLoader('Doctrine\ODM', __DIR__ . '/../lib/vendor/odm/lib');
    $classLoader->register();

    $classLoader = new ClassLoader('Doctrine\ODM', __DIR__ . '/../lib/vendor/doctrine2/lib');
    $classLoader->register();

    $classLoader = new ClassLoader('Entities', __DIR__.'/../lib');
    $classLoader->register();

  }
}

4. Create your classes in lib/Entities, ie. lib/Entities/Server.php:

namespace Entities;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;

class Server
{
  private $id;
  private $hostname;
  private $ipAddress;
  private $status = 0;

    public function getId()
    {
        return $this->id;
    }

    public function getHostname()
    {
        return $this->hostname;
    }
    public function setHostname($hostname)
    {
        $this->hostname = $hostname;
    }
   public function getIpAddress()
    {
        return $this->ipAddress;
    }
    public function setIpAddress($ip)
    {
        $this->ipAddress = $ip;
    }

  public function  __toString()
  {
    return $this->hostname;
  }

}

5. Now you can perform your operations, just to keep it simple, we will add the code to the actions.inc.php:

use Doctrine\ODM\MongoDB\EntityManager, Doctrine\ODM\MongoDB\Mongo, Entities\Server;
class defaultActions extends sfActions
{
 public function executeInex(sfWebRequest $request)
  {
    $em = EntityManager::create(new Mongo());

    $s = new Server();
    $s->setIpAddress('192.168.0.1');
    $s->setHostname('abc.example.com');
    $em->persist($s);
    $em->flush();
    $query = $em->createQuery('Entities\Server');
    $servers = $query->execute();
    $this->servers = $servers;
  }

And your indexSuccess.php has nothing special about ODM:

Servers:
<ul>
<?php foreach( $servers as $s): ?>
 <li><?php echo esc_entities($s);?></li>
<?php endforeach; ?>
</ul>

Hopefully with this preview, you can see the power of MongoDB when joined by ODM and symfony.

Special thanks to Jon Wage for leading the development of this project and his contribution to this article.

28

04 2010

Interesting symfony plugins: sfSyncContentPlugin

With the amount of plugins published in the symfony site, many great plugins get lost in the maze. With this series of posts, we would like to bring some attention to plugins we use every day or that we think are essential for any symfony developer.

sfSyncContentPlugin

Deploying symfony applications is always a key part of developing and maintaining websites that run on symfony. It is always a recommended practice to do development on a local environment or dedicated development server. It is also recommended to have a QA/staging server that is as close as possible to your production server. Using this well proven method you can spot problems and bugs before everybody else sees or experiences them, you know, those bugs that “only” happen in production, don’t tell me that it never happened to you, I won’t believe you.

Anyway, making changes in a live site is not only not recommended, it should never be done!

When developing and testing symfony applications, a lot of times you need to have a copy of the live data. Or you may have a staging server where you make changes before pushing them to a live site in a production server. symfony already provides a way to deploy code changes to a remote server, but what about uploaded and data files? And database content?

Since we discovered and started using it, we can’t live without the sfSyncContentPlugin plugin by Tom Boutell and Alex Gilbert, also developers of Apostrophe CMS. This plugin helps with all the tasks and needs described above. Using it is quite simple. All you need to do is define your servers in config/properties.ini like this:

[qa]
  host=qa.example.com
  port=22
  user=user
  dir=/var/www/mysite

[prod]
  host=www.example.com
  port=22
  user=user
  dir=/var/www/mysite

[staging]
  host=staging.example.com
  port=22
  user=user
  dir=/var/www/mysite

Make sure to use SSH keys to authenticate to your remote servers, so you don’t get asked again and again for passwords. Then just run the following symfony tasks:

# Migrate files and DB from development to qa
./symfony project:sync-content frontend dev to qa@qa

# Migrate files and DB to production (always make a backup of production before doing this!)
./symfony project:sync-content frontend dev to prod@prod

# Migrate files and DB from QA into development
./symfony project:sync-content frontend dev from prod@prod

Files and DB content are copied accordingly, almost magically. It saves so much time, but please make sure you understand and check the order that you apply in the symfony task. With the power this plugin provides, is very easy, by mistake, to overwrite production data, so again, always make a backup!

26

04 2010

Interesting symfony plugins: sfPropelMigrationsLightPlugin

You probably have read about all the buzz surrounding Doctrine these days. Its support for migrations (the ability to upgrade/downgrade the database schema) is pretty awesome. However, migrating to Doctrine from Propel 1.4 can be challenging on a large scale project. Don’t fret, it turns out that there is a cool little plugin that provides migrations for those that are locked in the Propel world. As described in the plugin page, the sfPropelMigrationsLightPlugin allows to “Easily change the database structure without losing any data.”

The main difference between Doctrine’s migrations and sfPropelMigrationsLightPlugin is that you have to write the code to alter your tables, where as Doctrine can generate these by looking at the differences in the local schema file and the DB. The plugin page describes the use which is fairly simple: create the migration class, add the code to the up() and down() methods and finally run the migrate task (ie. symfony migrate frontend 42)

Automating the deployment process is an important part of delivering software and avoiding problems. This plugin surely helps in this regard and we recommend its use if you are using Propel. And remember to always backup before you migrate anything!

06

04 2010

Installing Apostrophe CMS on shared hosting

Here is a quick guide to get Apostrophe CMS, up and running on our Shared hosting servers.

We are going to assume that you either have Apostrophe running on your local development environment, or that you will install the sandbox version that you can download from the site.

Installing the Apostrophe Sandbox

First of all, login to your Control Panel account and make sure you have SSH enabled for your domain. This can be done in the Setup section of the domain.

Enabling SSH

Enabling SSH

Next, in the Control Panel, go ahead and create your database and database user. Go to Databases under your domain and add a new database and then a new username.

Next, connect with your SSH client go to /symfony_projects directory and execute:

svn co http://svn.apostrophenow.org/sandboxes/asandbox/branches/1.3 asandbox

Once it finished executing all the SVN checkouts, you will have a complete Apostrophe installation in asandbox. Go into asandbox directory and create copies of the needed configuration files:

cd asandbox
cp config/databases.yml.sample config/databases.yml
cp config/properties.ini.sample config/properties.ini

Edit config/databases.yml and configure the database connection with the database/username created in the previous step. Make sure to change dbname, host, username and password to match your account.

all:
  doctrine:
    class:        sfDoctrineDatabase
    param:
       dsn:        mysql:dbname=ademo;host=sg108.servergrove.com
       username: ademo
       password: yourpassword

Run the following symfony tasks:

./symfony cc
./symfony plugin:publish-assets
./symfony doctrine:build --all
./symfony doctrine:data-load

This will create the default database and load the default configuration. You can also setup a default demo by running:

./symfony apostrophe:demo-fixtures

And finally run:

./symfony project:permissions

Before you are done there is a very important step. You need to configure the web server to use your Apostrophe installation. Go into the control panel and into the Maestro section. Select the asandbox project and go to Setup WebServer and click OK.

Setting up Apostrophe with Maestro

Setting up Apostrophe with Maestro

At this point, your Apostrophe installation has to be working, so go ahead and load your site

Apostrophe demo running

Installing Apostrophe from your development environment

If you have Apostrophe running in your development environment there are many common steps with the sandbox installation. First, enable SSH and create the database and database user in the Control Panel as described above. Then import a SQL dump of your database and import it using the DB WebAdmin in the Control Panel.

Next, upload your Apostrophe project into symfony_projects. You can upload the files using a FTP client or you can checkout your SVN repository or clone your GIT repository using the SSH client. Edit databases.yml so the connection information matches the shared hosting server settings as done in the sandbox installation above.

Next, run the following commands

./symfony cc
./symfony plugin:publish-assets
./symfony project:permissions

And finally, use Maestro as described in the sandbox installation to setup the web server to use Apostrophe project. It is that simple!

24

03 2010