Doctrine Instantiator

The Doctrine Project is a very big project, used and integrate in many PHP projects or libraries. It’s a set of package, whose the best known is probably the ORM build on top of the DBAL package. But there’re also many great packages like the Annotation, the Collections or the Cache. They are standalone and can be installed with Composer. So whatever is already used in your project, you can pick whatever you need in.

Let’s go deeper in a very small but very important doctrine project: the Instantiator!

A small, lightweight utility to instantiate objects in PHP without invoking their constructors

I’ve really enjoy reading the code source of this project, because it take advantages of every PHP possibility.

Usage of the package:

$instantiator = new \Doctrine\Instantiator\Instantiator();

$instance = $instantiator->instantiate(\My\ClassName\Here::class);

Exploring the code:

Usage of static variable

All the processed data are stored in differents static variable. It allow to share the cache in the runtime, anywhere you are.

Call an array like a method

Yes, if the first key of you array is an object instance and the second key is the name of a method in your previously object instance, then you can call the array like a function.

Create object from string serialized

When reflection is over, and we really need this new object instance without using the constructor, it use this nice hack. It create the string that represent the object serialized with PHP.

Using do/while

The usage of a do/while is very efficient when browsing throught class heritage to find if class is defined internally by the core or by the user.

I hope you’ve liked this article, different from what I’ve already writing.

--

--

Symfony lover, Gopher and opensource enthusiast. Ex-firefighter 🚒, I miss cuting out cars 🚙.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Thomas P

Thomas P

Symfony lover, Gopher and opensource enthusiast. Ex-firefighter 🚒, I miss cuting out cars 🚙.