Download the PHP package carloswph/tonton without Composer
On this page you can find all versions of the php package carloswph/tonton. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download carloswph/tonton
More information about carloswph/tonton
Files in carloswph/tonton
Package tonton
Short Description Serie of tools based on traits that simplify the use of singletons, multitons and other class instances controllers.
License MIT
Informations about the package tonton
TonTon PHP
Singleton patterns are amongst the most used structures in PHP. Together with that, some similar constructions, such as the Multiton, appear in almost every new PHP project. However, singletons could be much more. Initially, they don't really need to be inserted in any class, several times. Some people use abstracts, but does it make sense, extending a class which is just a support, by definition?
Also, some patterns could be deriving from the Singleton, beyond the Multiton, so that is what we are proposing here:
- First, use Singletons and similar as traits, to avoid duplicates and repetition while coding
- Second, create new and different subpatterns that can elevate the initial purpose of a Singleton to something even more useful
Installation
TonTon is available as PHP library, being installed through Composer.
Usage
Well, for the first two traits, "using" them is pretty much what you need to do. As traits, once they are required with Composer, they can easily be added to any class through the use
keyword inside the class. The usage is quite simple - let's consider a class named EasyPeasy
:
But the Singleton here is just the tip of the iceberg. If you want, by any reason, to have multiple instances of your class, but all of them need to be flagged (let's say one for dealing with queries, and other for logging processes), you'd prefer to use a Multiton instead. The approach will be basically the same:
But let's say, besides using many instances of that class, you want the number of instances to be limit, and you'd like to set this limit while creating your class. That can now be done using the Limiton:
Another useful "ton". Let's say we want to work with different instances of a class. For some of them, we want the object to be cached, but not for others. Also, the expiring time is to be different from instance to instance. Now we can solve this problem with Cacheton. For the moment, this script require Memcached class - which means php-memcached extensions must be installed.
Ok, now let's try something more interesting. It's not rare at all to see situations in which devs use Singletons in tandem with some constraints checkings, in the same class. Starting with the obvious, what if we came up with a Singleton that JUST creates a single instance if requirements are met?
That's exactly what we can do with the Selecton: