I want to add some functionality to a type provided by a framework, but this type is a singleton.
Thus, it's constructor is private. My class is supposed to be singleton too, but I have no idea how to get it initialized. I cannot alter code of original class.
Now I do not extend, just keep a private property that gets initialized in my getInstance, and use __call(), but it's insufficient and not intuitive to use. I can't pass my objects where originall class is expected.
You will need to keep the constructor in your extended class private. However, you could either do the following:
class originalClass
{
private function __construct()
{
/* Do something */
}
public static function init()
{
self::__construct();
}
}
class extendedClass extends originalClass
{
private function __construct()
{
parent::init();
}
public static function init()
{
self::__construct();
}
}
$var = extendedClass::init();
Alternatively, you could opt to have your class as a standalone, and use a magic method to access the 'parent' object:
class pdoExtender
{
private $someProperty;
public function __construct()
{
$this->someProperty = new PDO(...);
}
public function __call($name, $args)
{
if(method_exists(array($this, $someProperty), $name))
{
return call_user_func_array(array($this, $someProperty), $args);
}
}
}
// Example function calls:
$db = new pdoExtender;
// As (obj)pdoExtender doesn't have the method 'prepare()', the __call() method is invoked to check the 'parent' object, PDO
$db->prepare();
Related
I have a Factory Method to instance a class. Is there a way to prevent this class from direct instancing?
The only option I see is to use an argument passed into the __construct(), but that's not something I'm looking for.
On the other hand, making the __construct() private would be ideal, but I don't want MyClass to extend the Factory without actual need.
What do you guys think?
Factory Method:
class Factory
{
public static function instance()
{
return new MyClass(true);
}
}
MyClass:
class MyClass
{
public function __construct($isFactory = false)
{
if (!$isFactory) {
throw new Exception('Use Factory::instance() to create an object');
}
}
}
There are hacks to do that:
abusing inheritance to use a protected constructor
putting the factory method inside the class so that it can call the private constructor, which is actually not a hack. But then why not using the constructor in the first place?
using reflection to access the private constructor
I'm not promoting anything of that. What I personally do is documenting the API with things like #internal and leave it to the client following that contract.
In essence, your code should have read something like this:
THE FACTORY
<?php
class Factory {
public static function instance(){
return new MyClass(true); //HERE YOU ARE INSTANTIATING
}
}
THE CLASS TO BE INSTANTIATED VIA THE FACTORY
<?php
//NOT MyClass() <--- YOU ARE DEFINING.... NOT INSTANTIATING...
class MyClass {
public function __construct($isFactory = false) {
if (!$isFactory) {
throw new Exception('Use Factory::instance() to create an object');
}
}
//...MORE METHODS
}
Could you try this instead?
<?php
class Factory
{
private static $FACTORY_GUARANTOR; //ONLY SET DURING INSTANTIATION
public static function instance($type) {
if (class_exists($type)) {
self::$FACTORY_GUARANTOR = 1;
$instance = new $type();
self::$FACTORY_GUARANTOR = null;
return $instance;
}
else {
throw new Exception("Class not found...");
}
}
//YOU CAN GET $FACTORYGUARANTOR EXTERNALLY BUT NEVER SET IT;
public static function getGuarantor(){
return self::$FACTORY_GUARANTOR;
}
}
class MyClass {
protected $property1;
protected $property3;
protected $property2;
public function __construct() {
// IF SOMEONE TRIES TO INSTANTIATE THE CLASS OUTSIDE OF THE FACTORY... BLOW A WHISTLE
if(!Factory::getGuarantor()){
throw new Exception('Use Factory::instance() to create an object');
}
// IF THE PROGRAM MADE IT TO THIS POINT;
// JUST INSTANTIATE THE CLASS BECAUSE MOST LIKELY IT IS COMING FROM THE FACTORY
var_dump($this); // A LITTLE CONFIRMATION....
}
//...MORE METHODS
}
// TRY IT OUT:
/*INSTANCE A: RIGHT*/ $theClass = Factory::instance("MyClass"); //INSTANTIATES THE CLASS
/*INSTANCE B: WRONG*/ $theClass = new MyClass(); //THROWS AN EXCEPTION
The easiest way is to define your base class as abstract. The abstract classes cannot be directly instanced, so you will have to redefine their abstract members in the inherited classes:
abstract class Factory
{
abstract public function foo();
}
class InheritedClass extends Factory
{
public function foo()
{
// Do something
}
}
// $obj1 = new Factory(); // Will produce an error
$obj1 = new InheritedClass(); // Will be executed successfully
You can read more for the abstract classes here: PHP: Class Abstraction - Manual.
For me, the best way is to use ReflectionClass:
class MyClass
{
public const FRIEND_CLASSES = [Factory::class];
protected function __construct() {}
}
trait Constructor
{
protected function createObject(string $className, array $args = [])
{
if (!in_array(static::class, $className::FRIEND_CLASSES)) {
throw new \Exception("Call to private or protected {$className}::__construct() from invalid context");
}
$reflection = new ReflectionClass($className);
$constructor = $reflection->getConstructor();
$constructor->setAccessible(true);
$object = $reflection->newInstanceWithoutConstructor();
$constructor->invokeArgs($object, $args);
return $object;
}
}
class Factory
{
use Constructor;
public function MyClass(): MyClass
{
return $this->createObject(MyClass::class);
}
}
In constant FRIEND_CLASSES you can define in which classes the class can be instanced.
trait is used because this functionality can be used in different factories that are not related.
If you need to put parameters into constructor of the class, put them as second parameter of createObject.
Details I described in the article "Forbidding of creating objects outside factory in PHP"
So you can't make an abstract static function in php.
The alternatives as I see them are to:
Make the function non-static and write extra boilerplate code to create and store the object so I can access that function.
abstract class Foo {
abstract public function bar();
}
abstract class Good {
public function bar() {
...
}
}
// boilerplate to access Good->bar()... potentially a lot in multiple files
$g = new Good();
$g->bar();
Fill in the static function in my abstract class with a BadMethodCallException, so that any call to a child class which doesn't implement it will throw the exception.
abstract class Foo {
public static function bar() {
throw new BadMethodCallException("Not Implemented By Child Class :(");
}
}
class Good extends Foo {
public static function bar() {
// ...
}
}
class Bad extends Foo {
// no bar implementation
}
Good::bar(); // works
Bad::bar(): // exception
I'm leaning towards 2. but was wondering if there's any community consensus on this issue or best practices.
I ended up making an interface with a static function, then implementing the interface in the abstract class. This forces the child classes to define the method, which is basically what I wanted with an abstract static function.
interface ModelFactoryInterface {
public static function offer();
}
abstract class ModelHelper implements ModelFactoryInterface {
protected $tester;
public function __construct($tester) {
$this->tester = $tester;
}
}
/* Location
* ------------------------------------------------------ */
final class LocationHelper extends ModelHelper {
public static function offer() {
return new Location(...)
}
}
To be specific, i have a two class Request and Utils,
class Request
{
public function __construct()
{
//constructor method
}
public function request()
{
$utils=new Utils;
$consolidated_errors=$utils->array_remove_empty($all_params_error);
}
public function process()
{
$utils=new Utils;
$consolidated_errors=$utils->another_method($all_params_error);
}
}
And class Utils,
class Utils
{
public function __construct()
{
//constructor method
}
public function array_remove_empty()
{
//returns a variable.
}
public function another_method()
{
//returns a variable.
}
}
you can see that i am initializing the class two times in request class , and my question is that any way initializing the class globally and using through out the class?
You are looking for Singleton pattern
Following demonstrate very basic Singleton example for your class
public class Utils {
private static Utils uniqInstance;
private Utils() {
}
public static synchronized Utils getInstance() {
if (uniqInstance == null) {
uniqInstance = new Utils();
}
return uniqInstance;
}
// other useful methods here
}
get the instance using static-factory pattern
The above code does not look like Java to me, but anyway,
You could create the class at a class level private Utils myUtuils = new Utils ();
or
have the class as a static class and then just use it directly in your method
public function process()
{
consolidated_errors= Utils.another_method($all_params_error);
}
}
Is it ok to put factory() method to the factoried object's class?
class User {
public static function factory($id) {
return new User($id);
}
private function __construct($id) {
}
}
And when consider placing factory() method into separated class?
class User {
public function __construct($id) {
}
}
class UserFactory {
public static function factory($id) {
return new User($id)
}
}
I can't see any benefits of using additional class for factory, but I consider that there are some benefits I don't know about. :)
When to put factory() method into factoried object and when put factory() method to separated class?
The advantage with putting the factory method inside the class itself is protecting the class from being instantiated without using the factory method:
class User {
public static function factory($id) {
return new User($id);
}
private function __construct($id) {
// Now, only the factory method within this class can call this method.
// (Additionally, this method was static, which it shouldn't.)
}
}
I let other add to this with advantages of the opposite solution.
If you have a static creator method there is not much use in putting in into a factory.
It's only really useful to put factory method in it's own class if it isn't static and you want to inject it somewhere.
class User {
public static function __construct($id) {
}
}
class UserFactory {
public function factory($id) {
return new User($id)
}
}
class SomethingUserReleated {
public function __construct(UserFactory $factory) {
$this->userFactory = $factory;
}
public function iNeedToCreateAnUserForSomething() {
$userOne = $this->userFactory->factory(1233);
$userTwo = $this->userFactory->factory(123533);
}
}
Since you can't to the above with static methods.
Moving the factory methods into separate class allows you to separate object-methods and factory-specific methods (that are only needed while creating a new object).
class User {
public static function __construct($id, $name){
// call this directly or via Factory
}
}
class UserFactory {
private static function randomName(){
// return some random name
}
public static function factory($id){
return new User($id, UserFactory::randomName());
}
}
When creating a Singleton in PHP, I ensure that it cannot be instantiated by doing the following:
class Singleton {
private function __construct() {}
private function __clone() {}
public static function getInstance() {}
}
However, I realised that defining a class as 'abstract' means that it cannot be instantiated. So is there anything wrong with doing the following instead:
abstract class Singleton {
public static function getInstance() {}
}
The second scenario allows me to write fewer lines of code which would be nice. (Not that it actually makes much of a difference.)
When creating a singleton in PHP, declaring the __construct and __clone as private ensures that the class cannot be instanciated from the outside : it can still be instanciated from inside its declaration.
When declaring a class as abstract, it can not be instanciated at all ; not even from inside its declaration.
This means your solution would not work : in the second case, your getInstance() method will not be able to instanciate the class -- while it can do so in the first case.
No because then then you can't instantiate the class at all (not even in the static getInstance method). The private constructor in the singleton example just assures, that only the static getInstance method from the same class can access the constructor.
No, you cannot use an abstract class instead of a private __construct() when creating a singleton. But if your intention is to create an Abstract Singleton from which to extend from, you can do so like this:
abstract class Singleton
{
private static $_instances;
public static function getInstance()
{
$className = get_called_class(); // As of PHP 5.3
if(! isset(self::$_instances[$className] )) {
self::$_instances[$className] = new $className();
}
return self::$_instances[$className];
}
protected function __construct( ) {}
final private function __clone( ) {}
final private function __wakeup( ) {}
}
You can then extend from Singleton like this:
class Foo extends Singleton {
protected $_foo = 1;
public function setFoo($i) { $this->_foo = $i; }
public function getFoo() { return $this->_foo; }
}
and
class Bar extends Singleton {
protected $_foo = 1;
public function setFoo($i) { $this->_foo = $i; }
public function getFoo() { return $this->_foo; }
}
and manipulating:
$foo1 = Foo::getInstance();
$foo1->setFoo(5);
$foo2 = Foo::getInstance();
var_dump($foo2);
$bar1 = Bar::getInstance();
var_dump($bar1);
echo new ReflectionObject($foo2);
echo new ReflectionObject($bar1);
However, keep in mind that Singletons are very hard to unit-test and should be avoided if possible. See my answer here for some background:
How to remove multiple instances and just have one instance while multiple function calls in php?
Is there a use-case for singletons with database access in PHP?
It could work if your Singleton::getInstance() is supposed to return an instance of a different class.
abstract class Singleton {
public static function getInstance() {
static $instance = null;
if ( is_null($instance) ) {
$instance = new StdClass; // a different class than 'abstract class Singleton'
$instance->x = time();
}
return $instance;
}
}
$obj = Singleton::getInstance();
But I'd find that confusing. A bit like misusing abstract to combine the complexity of an abstract factory with the restraints of a singleton.