Remove the new for your propel entities in your code

The way to the component

I love to write unit tests and furthermore, I am addicted to dependency injection. Last but not least, I really like the propel orm and the behaviors.

First, I was getting annoyed that I was not able to remove the new MyObject() in the code I wanted to test. This is super bad since you really want to call the $myObject->save() method which leads to the fact that you either have to do some magic shit by mocking the whole database or by preparing the database, running the test and clean up the database afterwards.

So, the first approach wasn't that cool. Second idea was to implement a createEntity() method in the MyObjectQuery class. This was nice since I am injecting and mocking the query class whenever possible. But there was one downside with this approach. It didn't played well with my finger laziness ;-).

Third approach is the current and final solution. I created a behavior for this. Code speaks louder than words, so lets see what you can do when using this behavior.

$myQuery = MyQuery::create();

$myEntity = $myQuery->createEntity();   //creates a new entity of class "My" without using new


The installation is easy and well described here.

cd <in your project path>
composer require net_bazzline/php_propel_behavior_create_entity:1.1.*

Afterwards you have to adapt your propel.ini and add the following line at the end.

propel.behavior.create_entity.class = lib.vendor.net_bazzline.php_propel_behavior_create_entity.source.CreateEntityBehavior

Finally add either in your schema.xml in the database section (for complete support) or in some table section (for partial support).


The API is available at

Tags: behavior, bazzline, composer, english, free_as_in_freedom, github, opensource, packagist, propel