Skip to main content

Posts

Showing posts from November, 2011

Mapping embedded documents in Doctrine MongoDB ODM

If you have a MongoDB document that has another document embedded in it, you still have to create a separate XML mapping document for the embedded one. So if you have a parent document called Activity that has an embedded document called Coordinates , the configuration would look something like this: src/Acme/ActivityBundle/Resources/config/doctrine/Activity.mongodb.xml <doctrine-mongo-mapping xmlns="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping http://doctrine-project.org/schemas/odm/doctrine-mongo-mapping.xsd"> <document name="Acme\ActivityBundle\Document\Activity" db="acme" collection="activity" customId="true"> <field fieldName="id" id="true" strategy="INCREMENT...

Creating a Symfony2 helper

While working on a Symfony2 project yesterday, I realized I needed a better way to format dates in my templates. The reason behind this was the fact that my MongoDB document entities contained date values that were either null or DateTime instances. This entailed using a bunch of if statements for extra checks that made template code unnecessarily verbose. My solution was to create a template helper in an application specific framework bundle that I had created previously to contain all common assets and other necessary common resources. Create a Helper directory in the framework bundle directory and create a DateHelper class: src/Acme/FrameworkBundle/Helper/DateHelper.php namespace Acme\FrameworkBundle\Helper; use Symfony\Component\Templating\Helper\Helper; class DateHelper extends Helper { protected $options; public function __construct(array $options) { $this->options = $options; } public function getName() { return ...

Adding post-login logic to FOSUserBundle

Having finally figured out how to use FOSUserBundle in my project, I decided to keep track of all logins next. The implementation turned out to be a breeze thanks to Symfony2's security listener mechanism. As usual, the first step is to create a MongoDB document for this purpose. This is a very simple document that contains a user's id, session id, IP address, and login date. src/Acme/UserBundle/Document/LoginHistory.php namespace Acme\UserBundle\Document; class LoginHistory { protected $id; protected $userId; protected $sessionId; protected $ip; protected $createdAt; /** * Get id * * @return custom_id $id */ public function getId() { return $this->id; } /** * Set userId * * @param int $userId */ public function setUserId($userId) { $this->userId = $userId; } /** * Get userId * * @return int $userId */ public function getUserId...