Advice on Factory Method - php

Using php 5.2, I'm trying to use a factory to return a service to the controller. My request uri would be of the format www.mydomain.com/service/method/param1/param2/etc. My controller would then call a service factory using the token sent in the uri. From what I've seen, there are two main routes I could go with my factory.
Single method:
class ServiceFactory {
public static function getInstance($token) {
switch($token) {
case 'location':
return new StaticPageTemplateService('location');
break;
case 'product':
return new DynamicPageTemplateService('product');
break;
case 'user'
return new UserService();
break;
default:
return new StaticPageTemplateService($token);
}
}
}
or multiple methods:
class ServiceFactory {
public static function getLocationService() {
return new StaticPageTemplateService('location');
}
public static function getProductService() {
return new DynamicPageTemplateService('product');
}
public static function getUserService() {
return new UserService();
}
public static function getDefaultService($token) {
return new StaticPageTemplateService($token);
}
}
So, given this, I will have a handful of generic services in which I will pass that token (for example, StaticPageTemplateService and DynamicPageTemplateService) that will probably implement another factory method just like this to grab templates, domain objects, etc. And some that will be specific services (for example, UserService) which will be 1:1 to that token and not reused. So, this seems to be an ok approach (please give suggestions if it is not) for a small amount of services. But what about when, over time and my site grows, I end up with 100s of possibilities. This no longer seems like a good approach. Am I just way off to begin with or is there another design pattern that would be a better fit? Thanks.
UPDATE: #JSprang - the token is actually sent in the uri like mydomain.com/location would want a service specific to loction and mydomain.com/news would want a service specific to news. Now, for a lot of these, the service will be generic. For instance, a lot of pages will call a StaticTemplatePageService in which the token is passed in to the service. That service in turn will grab the "location" template or "links" template and just spit it back out. Some will need DynamicTemplatePageService in which the token gets passed in, like "news" and that service will grab a NewsDomainObject, determine how to present it and spit that back out. Others, like "user" will be specific to a UserService in which it will have methods like Login, Logout, etc. So basically, the token will be used to determine which service is needed AND if it is generic service, that token will be passed to that service. Maybe token isn't the correct terminology but I hope you get the purpose.
I wanted to use the factory so I can easily swap out which Service I need in case my needs change. I just worry that after the site grows larger (both pages and functionality) that the factory will become rather bloated. But I'm starting to feel like I just can't get away from storing the mappings in an array (like Stephen's solution). That just doesn't feel OOP to me and I was hoping to find something more elegant.

I think there is no way to avoid this token-service-mapping maintaining work when your site growing large. No matter how you implement this list, switch block, array, etc. this file will become huge someday. So my opinion is to avoid this list and make each token a service class, for those generic services, you can inherit them, like this
class LocationService extends StaticPageTemplateService {
public function __construct(){
parent::__construct('location');
}
}
class ServiceFactory {
public static function getInstance($token) {
$className = $token.'Service';
if(class_exist($className)) return new $className();
else return new StaticPageTemplateService($token);
}
}
in this way, you can avoid to edit the factory class file each time a token added or changed, you just need to change the specific token file.

I have a better factory pattern solution that will allow you to add new services without doing anything more than creating a new class for that specific service. Outlined below:
For the Factory:
class ServiceFactory{
private static $instance = null;
private static $services = array();
private function __construct(){
// Do setup
// Maybe you want to add your default service to the $services array here
}
public function get_instance(){
if($this->instance){
return $this->instance;
}
return $this->__construct();
}
public function register_service($serviceName, $service){
$this->services[$serviceName] = $service;
}
public function get_service($serviceName){
return $this->services[$serviceName]->get_new();
}
}
An Abstract Service:
include('ServiceFactory.php');
class AbstractService{
public function __construct($serviceName){
$factory = ServiceFactory::get_instance();
$factory->register_service($serviceName, $this);
}
public function get_new(){
return new __CLASS__;
}
}
And then a concrete service:
include('AbstractService.php');
class ConcreteService extends AbstractService{
// All your service specific code.
}
This solution makes your dependencies one way and you can add new services by simply extending the AbstractService, no need to modify any existing code. You call into the factory with the get_service('news') or whichever you want, the factory looks up the associated object in its $services array and calls the get_new() function on that particular object which gets you a new instance of the specific service to work with.

I'm not a PHP developer, so I'm not going to attempt to show any code, but here's what I would do. I would implement the Strategy Pattern and create an IServiceProvider interface. That interface could have a GetService() method. Then you would create four new objects: LocationService, ProductService, UserService, and DefaultService, all of which would implement the IServiceProvider interface.
Now, in your factory, the constructor would take in a IServiceProvider and have one public GetService() method. When the method is called, it will use the strategy of the injected IServiceProvider. This improves extensability as you won't have to open the Factory everytime you have a new service, you would just create a new class that implements IServiceProvider.
I decided quick to mock this up quick in C# so you would have an example. I understand this isn't the language you are using, but maybe it will help clarify what I'm saying. Code shown below.
public interface IServiceProvider
{
Service GetService();
}
public class UserServiceProvider : IServiceProvider
{
public Service GetService()
{
//perform code to get & return the service
}
}
public class StaticPageTemplateServiceProvider : IServiceProvider
{
public Service GetService()
{
//perform code to get & return the service
}
}
public class DynamicPageTemplateServiceProvider : IServiceProvider
{
public Service GetService()
{
//perform code to get & return the service
}
}
public class DefaultServiceProvider : IServiceProvider
{
public Service GetService()
{
//perform code to get & return the service
}
}
public class ServiceFactory
{
public ServiceFactory(IServiceProvider serviceProvider)
{
provider = serviceProvider;
}
private IServiceProvider provider;
public Service GetService()
{
return provider.GetService();
}
}

Service factory implementation (with an interface that we'll use in concrete classes):
class ServiceFactory
{
private static $BASE_PATH = './dirname/';
private $m_aServices;
function __construct()
{
$this->m_aServices = array();
$h = opendir(ServiceFactory::$BASE_PATH);
while(false !== ($file = readdir($h)))
{
if($file != '.' && $file != '..')
{
require_once(ServiceFactory::$BASE_PATH.$file);
$class_name = substr($file, 0, strrpos($file, '.'));
$tokens = call_user_func(array($class_name, 'get_tokens'));
foreach($tokens as &$token)
{
$this->m_aServices[$token] = $class_name;
}
}
}
}
public function getInstance($token)
{
if(isset($this->m_aServices[$token]))
{
return new $this->m_aServices[$token]();
}
return null;
}
}
interface IService
{
public static function get_tokens();
}
$BASE_PATH.'UserService.php':
class UserService implements IService
{
function __construct()
{
echo '__construct()';
}
public static function get_tokens()
{
return array('user', 'some_other');
}
}
So, what we're doing essentially is self-registering all tokens for any concrete class implementation. As long as your classes reside in $BASE_PATH, they'll automatically be loaded by the ServiceFactory when it's instantiated (of course, you could change ServiceFactory to provide this via static methods if you wanted to).
No need to have a big switch statement providing access to concrete implementations as they're all help in an internal map that's built by the get_tokens() function that are implemented at the concrete class level. The token->class relationship is stored in a 1:1 map within the service factory, so you'd need to refactor this if you're chaining tokens for whatever reason.

Here's how I do a singleton factory (comments removed for brevity):
Updated to better serve your purpose.
class ServiceFactory {
private static $instance;
private function __construct() {
// private constructor
}
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
public static function init() {
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
public function get_service($name, $parameter) {
$name .= 'TemplateService';
return $this->make_service($name, $parameter);
}
private function make_service($name, $parameter) {
if (class_exists($name)) {
return new $name($parameter);
} else {
throw new LogicException('Could not create requested service');
return false;
}
}
}
In it's simplest form like this, just pass a string name of the service:
function whatever() {
$ServiceFactory = ServiceFactory::init();
$new_service = $ServiceFactory->get_service('StaticPage', 'location');
return $new_service;
}

And some that will be specific services (for example, UserService) which will be 1:1 to that token and not reused. So, this
seems to be an ok approach (please give suggestions if it is not) for a small amount of services. But what about when, over
time and my site grows, I end up with 100s of possibilities. This no longer seems like a good approach. Am I just way off
to begin with or is there another design pattern that would be a better fit? Thanks.
Sorry to say, but I think you're now trying to solving a problem that you've created for yourself.
the token is actually sent in the uri like mydomain.com/location would want a service specific to
loction and mydomain.com/news would want a service specific to news. Now, for a lot of these, the
service will be generic. For instance, a lot of pages will call a StaticTemplatePageService in which
the token is passed in to the service. That service in turn will grab the "location" template or
"links" template and just spit it back out.
Some have already suggested using a Dependency Injection Container to solve the whole factory issue, but I wonder why there is a need for a factory in the first place? You seem to be writing a Controller (I guess), that can generate a response for a multitude of different types of request, and you're trying to solve it all in one class. I'd instead make sure that the different requests (/location, /news) map to dedicated, small, readable controllers (LocationController, NewsController). As one controller needs only one service this should be much easier to write, maintain and expand.
That way, you solve the dependencies in dedicated, concise, readable classes instead of one giant God class. That means you'll have no issues with a switch of hundreds of lines either, you should just map "location" to LocationController, "news" to NewsController, etc. A lot of PHP frameworks these days use a FrontController for that, and I imagine that is the way to go for you as well.
PS: to make sure the NewsService actually makes into the NewsController, I would suggest using a dependency injection container. It makes your life easier ;)

Related

Dependency Injection Container: Multiple instances of a single class

I am just starting with Dependency Injection Containers, and I am having a problem that makes my code messy. Let's take an example: I have a simple Container class that manages multiple services, a service can be "marked" as shared so it can only make one single instance.
So for example, I will make a simple (It's not the one I actually use) dependency injection container for, let's say, a User class, I would do so:
class Container
{
protected $parameters;
public function set($index, $value)
{
$this->parameters[$index] = $value;
}
public function getUser()
{
return new User($this->paramaters['id'], $this->parameters['nickname']);
}
}
$container = new Container();
$container->set('id', 1);
$container->set('nickname', 'Bob');
$container->getUser();
This works fine. But now, here is an other case: Let's say that now, instead of a User class, I want a Post class, for each post, I will need to set their title, text and date in the constructor, and each post shouldn't have the same parameters. In this case, is an dependency injection container adapted, if so, how should I achieve it without having a mess of a code?
Edit:
Will asked me my use case:
In my use case, I am actually doing this with a Router class that need to use Route instances. Each instantiated Route need to be passed two arguments: the pattern and the callback. So each time I ask my container to create a Route instance, it shouldn't use for all Routes the same pattern and callback, but a new pair of them (pattern + callback). How should I do so?
Your goal here is to create a Shared Abstraction which can be injected into the code that depends on its data. There's two approaches you can take, and I think you're mixing the two already.
A Generic Dependency-Injection Container - In this case, we make a very generic object that can store and retrieve other objects. An example is here:
<?php
class Container
{
protected $dependencies = array();
public function get($key)
{
return isset($this->dependencies[$key]) ? $this->dependencies[$key] : null;
}
public function register($key, $value)
{
$this->dependencies[$key] = $value;
}
}
You can then use the container like this:
$container = new Container();
$container->register('user', new User(1, 'Bob'));
$container->register('somethingElse', new SomethingElse(42));
And then you can just pass $container to another function, method, or object, where you can do:
$user = $container->get('user');
There are also many Open Source containers you can use like Pimple, or PHP-DI.
A Domain-Specific Shared Abstraction - Another approach is to make a specific shared abstraction, like, in your case, a UserPost perhaps:
<?php
class UserPost
{
protected $user;
protected $post;
public function __construct(User $user, Post $post)
{
$this->user = $user;
$this->post = $post;
}
public function getUser()
{
return $this->user;
}
public function getPost()
{
return $this->post;
}
}
You can then simply inject the UserPost and call $userPost->getUser() / $userPost->getPost(). The second method here is basically as simple as coming up with a name for the combination of data items you wish to pass. I prefer this approach, as it makes the code more readable, but this is a matter of opinion. I prefer to have my classnames correspond to "what I think of this object as" in plain English. This also aligns more closely with the core-OO principals of abstraction, in my opinion. But, the generic containers in Option 1 is an approach used successfully by many.

Where to implement a factory method?

I've been trying to grasp OOP concepts and while I do get the general ideas behind most of them, I often find myself in need of some advice regarding their practical implementation. One of such cases is the factory method.
I'm writing a PHP app that's going to handle requests incoming from both web and command-line interface, so I came up with the following simple class inheritance structure to cover both types of requests:
abstract class Request {
}
class HttpRequest extends Request {
}
class CliRequest extends Request {
}
Now I need a factory method that would return a concrete Request instance, depending on the value returned by php_sapi_name():
public function create() {
if(php_sapi_name() === 'cli')
return new CliRequest();
else
return new HttpRequest();
}
My question is: where do I put it? I can think of at least three possibilities:
1) Static method in a separate class:
class RequestFactory {
public static function create() {
// ...
}
}
2) Regular method in a separate class (would require instantiating the class first):
class RequestFactory {
public function create() {
// ...
}
}
3) Static method in the abstract parent class:
abstract class Request {
public static function create() {
// ...
}
}
What are the pros and cons of each solution and which would be considered "proper" and why?
All these possibilities will work as expected. I don't really get any "cons" as it fulfils, what is IMHO, your encapsulation objective.
Now, let's look at Factory Method pattern essence:
Define an interface for creating an object, but let the classes that
implement the interface decide which class to instantiate. The Factory
method lets a class defer instantiation to subclasses.
I'm not sure if what you're willing to do perfectly matches this definition.
Instead, it looks like you want to implement something called "Simple Factory" in which instantiation process is encapsulated into a class.
But having this kind of method directly into the abstract class that defines the interface of your "Request" objects doesn't look like a bad idea.
As Nicolas said, it's a rather common pattern in Java, C#, and Cocoa lands.
For these reasons, my choice would go to 3rd option
So, I have an idea, to do what I think you want, using method overloading.
class Request {
private $request;
private $valid = true;
private $type;
private $vars;
private $methods;
public function __construct() {
$this->type = php_sapi_name() === 'cli' ? 'cli' : 'http';
if($this->is_cli()) $this->request = new CliRequest();
else if($this->is_http()) $this->request = new HttpRequest();
else {
$this->valid = false;
return;
}
$this->vars = get_class_vars($this->request);
$this->methods = get_class_methods($this->request);
}
public function __get( $var ){
if(!$this->valid) return false;
if(!in_array($var, $this->vars)) return false;
return $this->request->$var;
}
public function __set( $var , $val ){
if(!$this->valid) return false;
if(!in_array($var, $this->vars)) return false;
return $this->request->$var = $val;
}
public function __call( $meth, $args ){
if(!$this->valid) return false;
if(!in_array($meth, $this->methods)) return false;
return call_user_func_array($this->request->$var, $args);
}
public function is_cli( ){
return $this->type == 'cli';
}
public function is_http( ){
return $this->type == 'http';
}
}
// Then, when calling the function...
$request = new Request;
$request->variable; // will get the variable from the Cli or Http request class
$request->method("a","b","c"); // Will run the method from the Cli or Http request class
To create truely loosely coupled code you could use Ray.Di or Injektor and do something similar to the following:
<?php
use Ray\Di\Di\Inject;
use Ray\Di\Di\Scope;
/**
* #Scope("Singleton")
*/
abstract class Request {
}
class HttpRequest extends Request {
}
class CliRequest extends Request {
}
class ARequestConsumer {
/* #var Request */
private $request;
public function __construct( Request $request )
{
$this->request = $request;
}
public function foo()
{
//...
}
}
class Global extends Ray\Di\AbstractModule {
public function configure()
{
$this->bind( 'Request' )
->toProvider( 'RequestProvider' );
}
}
class RequestProvider implements \Ray\Di\ProviderInterface {
/**
* #return Request
*/
public function get()
{
//.. factory method logic goes here that produces a concrete instance of Request
}
}
$injector = Injector::create([new Global]);
$consumer = $injector->getInstance('ARequestConsumer');
$consumer->foo();
Using a static method in the parent class doesn't seem an awful solution to me at all.
Take a look at the Calendar class in Java: There's a getInstance method (many actually) which return a Calendar instance depending on your Locale, and some others criteria.
In this case I rather use the Base Abstract class as the creator of the Instance using the static method (3rd Option)
I will use an external class, like in the first option when I need to create some dependencies that Can break the encapsulation like having different dependencies for different implementations. and will turn the class less maintainable.
Design patterns are not restricted to OOP and a lot of implementations of OOP design patterns are written with some memory management in thought.
I come from the Java world and in Java you would have to use a strict OOP design pattern. Simply because everything in Java is an object. Sometimes you must create an object and a method even if it is actually not needed for the pattern itself. The factory method design pattern is such an example.
It is very good to design by interface for the implementations of the factory, but you don't need a class and method to implement the factory.
The reason that an implementation of a design pattern is sometimes confusing is that the programming language sometimes requires an implementation that is not strictly needed in the design pattern itself. The creation of a class with a method in the factory method is such an example.
My solution is not purely OOP, but PHP is that not too and in the long run is it not about OOP in my opinion, but about the best implementation of the design pattern factory method.
I think that the elegancy of PHP is that it combines best of both worlds. It delivers a solid OOP design possibility, yet it has not thrown away the good elements of procedural programming.
You can simply create code like this:
function createRequest($pRequesttype){
switch($pRequesttype){
case "cli":
$tmp = new CliRequest();
break;
case "http":
$tmp = new HttpRequest();
break;
default:
$tmp = new DefaultRequest();
}
return $tmp;
}
Always return a default implementation to handle the request.
A switch statement is the best choice to extend the number of choices in a software engineer friendly way.
Now have you the call php_sapi_name in your create function. I advice you to get it out the implementation of the function. It is best practice to let a function do one job only and getting the request and handling the request are two functions. Make a createRequest function that has a parameter like I showed you.
To answer your question:
1, 2 or 3? Uh, 4 actually. :-) If 1, 2 or 3?
Definitely 1, because I don't want to load too much classes for a simple method, but to simplify this situation I have proposed solution 4.
I would not use method 2, because it is not efficient to create a class for one moment in time. I would consider it best practice, but not the best practical implementation. If using this solution, then please also support the class with an interface for factories in general. Best OOP design, but not best practical implementation.
I would certainly not use method 3, because abstract classes are there to abstract data objects and interfaces to abstract behaviour. A factory method is an abstraction of an interface, never of an abstract class.

multi-level inheritance substitution

I want to write a module (framework specific), that would wrap and extend Facebook PHP-sdk (https://github.com/facebook/php-sdk/). My problem is - how to organize classes, in a nice way.
So getting into details - Facebook PHP-sdk consists of two classes:
BaseFacebook - abstract class with all the stuff sdk does
Facebook - extends BaseFacebook, and implements parent abstract persistance-related methods with default session usage
Now I have some functionality to add:
Facebook class substitution, integrated with framework session class
shorthand methods, that run api calls, I use mostly (through BaseFacebook::api()),
authorization methods, so i don't have to rewrite this logic every time,
configuration, sucked up from framework classes, insted of passed as params
caching, integrated with framework cache module
I know something has gone very wrong, because I have too much inheritance that doesn't look very normal. Wrapping everything in one "complex extension" class also seems too much. I think I should have few working togheter classes - but i get into problems like: if cache class doesn't really extend and override BaseFacebook::api() method - shorthand and authentication classes won't be able to use the caching.
Maybe some kind of a pattern would be right in here? How would you organize these classes and their dependencies?
EDIT 04.07.2012
Bits of code, related to the topic:
This is how the base class of Facebook PHP-sdk:
abstract class BaseFacebook {
// ... some methods
public function api(/* polymorphic */)
{
// ... method, that makes api calls
}
public function getUser()
{
// ... tries to get user id from session
}
// ... other methods
abstract protected function setPersistentData($key, $value);
abstract protected function getPersistentData($key, $default = false);
// ... few more abstract methods
}
Normaly Facebook class extends it, and impelements those abstract methods. I replaced it with my substitude - Facebook_Session class:
class Facebook_Session extends BaseFacebook {
protected function setPersistentData($key, $value)
{
// ... method body
}
protected function getPersistentData($key, $default = false)
{
// ... method body
}
// ... implementation of other abstract functions from BaseFacebook
}
Ok, then I extend this more with shorthand methods and configuration variables:
class Facebook_Custom extends Facebook_Session {
public function __construct()
{
// ... call parent's constructor with parameters from framework config
}
public function api_batch()
{
// ... a wrapper for parent's api() method
return $this->api('/?batch=' . json_encode($calls), 'POST');
}
public function redirect_to_auth_dialog()
{
// method body
}
// ... more methods like this, for common queries / authorization
}
I'm not sure, if this isn't too much for a single class ( authorization / shorthand methods / configuration). Then there comes another extending layer - cache:
class Facebook_Cache extends Facebook_Custom {
public function api()
{
$cache_file_identifier = $this->getUser();
if(/* cache_file_identifier is not null
and found a valid file with cached query result */)
{
// return the result
}
else
{
try {
// call Facebook_Custom::api, cache and return the result
} catch(FacebookApiException $e) {
// if Access Token is expired force refreshing it
parent::redirect_to_auth_dialog();
}
}
}
// .. some other stuff related to caching
}
Now this pretty much works. New instance of Facebook_Cache gives me all the functionality. Shorthand methods from Facebook_Custom use caching, because Facebook_Cache overwrited api() method. But here is what is bothering me:
I think it's too much inheritance.
It's all very tight coupled - like look how i had to specify 'Facebook_Custom::api' instead of 'parent:api', to avoid api() method loop on Facebook_Cache class extending.
Overall mess and ugliness.
So again, this works but I'm just asking about patterns / ways of doing this in a cleaner and smarter way.
Auxiliary features such as caching are usually implemented as a decorator (which I see you already mentioned in another comment). Decorators work best with interfaces, so I would begin by creating one:
interface FacebookService {
public function api();
public function getUser();
}
Keep it simple, don't add anything you don't need externally (such as setPersistentData). Then wrap the existing BaseFacebook class in your new interface:
class FacebookAdapter implements FacebookService {
private $fb;
function __construct(BaseFacebook $fb) {
$this->fb = $fb;
}
public function api() {
// retain variable arguments
return call_user_func_array(array($fb, 'api'), func_get_args());
}
public function getUser() {
return $fb->getUser();
}
}
Now it's easy to write a caching decorator:
class CachingFacebookService implements FacebookService {
private $fb;
function __construct(FacebookService $fb) {
$this->fb = $fb;
}
public function api() {
// put caching logic here and maybe call $fb->api
}
public function getUser() {
return $fb->getUser();
}
}
And then:
$baseFb = new Facebook_Session();
$fb = new FacebookAdapter($baseFb);
$cachingFb = new CachingFacebookService($fb);
Both $fb and $cachingFb expose the same FacebookService interface -- so you can choose whether you want caching or not, and the rest of the code won't change at all.
As for your Facebook_Custom class, it is just a bunch of helper methods right now; you should factor it into one or more independent classes that wrap FacebookService and provide specific functionality. Some example use cases:
$x = new FacebookAuthWrapper($fb);
$x->redirect_to_auth_dialog();
$x = new FacebookBatchWrapper($fb);
$x->api_batch(...);
It is indeed too much inheritance. Looks like a job for Facade design pattern. Use composition instead of inheritance to have more flexibility. Delegate any methods you use to appropriate objects.
For example if any of the underlying classes changes, you can just change your methods to adapt to the changes, and you won't have to worry about overriding any of the parent methods.
Generally yes, it is not a good idea to assign multiple responsibilities to one class. Here, the responsibility of the class would be to represent an external API.
I have done some thing like that for yahoo sdk let me put it, give it a try :)
Lets assume Facebook is the class in sdk you are using for all end method calls.
You can create a new class(as your frame work allows) and assign a variable of the class to the instance of the Facebook Class .
Use __call() for all methods of Facebook and put your custome ones in the wrapper class.
for all undefined methods it wrapper it will go to Facebook Class and there is no inheritance involved at all.
It worked for me . Hope it helps :)
Class MyWrapper
{
protected $facebook;
public function __construct()
{
$this->facebook = new FaceBook();
}
public function __call($method,$args)
{
return $this->facebook->$method($args);
}
///define Your methods //////////
///////////////////////////////////
}
$t = new MyWrap;
$t->api(); // Whatever !!!!
edited :
You don't need to create multiple wrapper for more than one classes following can be done,you just need to take care at the method call time, have to suffix the variable name holding instance of the wrapped class.
Class MyWrapper
{
protected $facebook;
protected $facebookCache;
public function __construct()
{
$this->facebook = new FaceBook();
$this->facebookCache = new FacebookCache();
}
public function __call($method,$args)
{
$method = explode('_',$method);
$instance_name = $method[0];
$method_name = $method[1];
return $this->$instance_name->$method_name($args);
}
///define Your methods //////////
///////////////////////////////////
}
$t = new MyWrap;
$t->facebook_api(); // Whatever !!!!
$t->facebookCache_cache();
i think repository design pattern will be better in this situation. although i am not from php but as per oops it should solve your issue..

Construction of a singleton class

An ethical question here.
I'm planning on using several manager classes in my new project that will be performing various tasks across the whole project. These classes are singletons, but require construction based on parameters.
As to when/where this construction has to happen, I have mixed feelings. I have these options so far:
Option A
It's easy to just pass these parameters to the getInstance method while having a default null value. On the very first call the parameters will be used, and any additional calls completely ignore them.
While this works, doing so feels rather unlogical, for the following reasons:
It makes documentation unclear. getInstance' first parameter must be of type Collection, but can be null... what's going on here?
You can argue that writing a line about this in the description will clear it up, but I'd prefer clarification to be unneccesary.
It feels faulty to pass getInstance any construction parameters. This is due to the fact that the method name does not explicity hint towards construction, making it unclear it will happen.
Option B
I'm thinking about a setup method. This method takes all parameters, calls the class constructor, and changes the internal class state to initialized.
When calling the getInstance method prior to setup, it will throw a NotInitializedException. After setup has been called, any additional calls to setup will result in a PreviouslyInitializedException.
After setup has been called, getInstance becomes available.
Personally, this option appeals more to me. But it feels excessive.
What option do you prefer? And why?
I would probably try and ditch the singleton approach and pass manager classes around to whatever needs them.
$manager = new Manager( $collection, $var, $var2 );
$other_class = New OtherClass( $manager );
//or
$other_class = New OtherClass;
$other_class->manager = $manager;
//or
$other_class = New OtherClass;
$other_class->setManager( $manager );
Use dependency injection to pass the Manager object around. Don't use Singleton pattern. It's a common consensus that using it creates a global state and makes your API deceptive.
PHP Global in functions (jump to answer)
Singletons are pathological liars
Inject the Manager instance to any class that needs it via the constructor. Each class should not try to instantiate Manager by themselves, the only way the classes get an instance of the Manager is by getting it from constructor.
class NeedsManager
{
protected $manager;
public function __construct(Manager $manager)
{
$this->manager = $manager;
}
}
You don't need to enforce one instance of Manager. Just don't instantiate it more than once. If all of your classes that need an instance of Manager get what they need from the constructor and never tries to instantiate it on their own, it will assure that there's just going to be one instance in your application.
How about option 3. If they are true singletons, set up properties files for their parameters for use with a no-arg getInstance.
If that doesn't fit, you might be misusing the singleton pattern.
You are looking at using a Factory design pattern. Factories are objects that act as fancy constructors for other objects. In your case, you will move setup and getInstance to the factory. The wiki article's pretty good- http://en.wikipedia.org/wiki/Factory_method_pattern
class SingletonFoo {
//properties, etc
static $singleton = NULL;
private function __constructor(){}
static function getInstance(){
if(NULL === self::$singleton) {
self::$singleton = new SingletonFoo();
}
return self::$singleton;
}
}
class FooFactory {
static $SingletonFoo = null;
static function setup($args){
if( !(NULL === self::$SingletonFoo)){
throw new AlreadyInstantiatedException();
}
self::$SingletonFoo = SingletonFoo::getInstance();
//Do stuff with $args to build SingletonFoo
return self::$SingletonFoo;
}
static function getInstance(){
if(NULL === self::$SingletonFoo) {
throw new NotInstantiatedException();
}
return self::$SingletonFoo;
}
}
Don't use Singleton, use Resources Manager (or Service Container, or DI Container):
class ResourceManager
{
protected static $resource;
public static function setResource($resource)
{
if (!empty(self::$resource)) //resource should not be overwritten
{
if ($resource!=self::$resource) return false;
else return true;
}
self::$resource = $resource;
return true;
}
public static function getResource()
{
return self::$resource;
}
}
Resource Manager allows you to set any custom classes for unit-testing (like dependency injection), you can just get needed resources without requesting them in constructor (I like DI, but sometimes it's just more handy to use empty constructors).
Ready-to-use variant: http://symfony.com/doc/current/book/service_container.html (I don't like to move logic from code to configs, but in stand-alone module it looks acceptable).

Dependency injection when you have no control over instantiation and usage

How is it done?
I have a Model class that is the parent to many sub-classes, and that Model depends on a database connection and a caching mechanism.
Now, this is where it starts getting troublesome: I have no control over how each object gets instantiated or used, but I have control over methods that get used by the sub-classes.
Currently I have resorted to using static methods and properties for dependency injection, as such:
class Model
{
private static $database_adapter;
private static $cache_adapter;
public static function setDatabaseAdapter(IDatabaseAdapter $databaseAdapter)
{
self::$databaseAdapter = $databaseAdapter;
}
public static function setCacheAdapter(ICacheAdapter $cacheAdapter)
{
self::$cacheAdapter = $cacheAdapter;
}
}
Which has worked out well, but it feels dirty (it creates a global state for all Models).
I have considered the factory pattern, but that removes the control of the instantiation from the sub-classes (how do I instantiate an object with a variable number of parameters in it's constructor?).
Now I am at a loss. Any help would be appreciated.
As far as I know this is a perfectly acceptable alternative. Another possibility suggested by Sebastian Bergmann, the creator of PHPUnit, is to have a $testing static property. You can read his recent article regarding the Testing of Singletons. It sounds like you have similar issues.
You're solution would be fine for setting default adapters, but I'd add a way for the individual models to have a different adapter. Consider this:
abstract class Model {
protected $_database_adapter;
protected $_default_database_adapter;
public function getDatabaseAdapter() {
if(!$this->_database_adapter) {
if(self::$_default_database_adapter) {
$this->_database_adapter = self::$_default_database_adapter;
} else {
throw new Exception("No adapter set yet");
}
}
return $this->_database_adapter;
}
public function setDatabaseAdapter(IDatabaseAdapter $databaseAdapter) {
$this->_database_adapter = $databaseAdapter;
}
public static function setDefaultDatabaseAdapter(IDatabaseAdapter $databaseAdapter) {
self::$_default_database_adapter = $databaseAdapter;
}
}
Of course you could extract all static methods/properties into a Registry, Container or anything else as central.
For example, perhaps you don't want to collect data from the same database host over your whole application. Then your original script would look like the following:
Model::setDatabaseAdapter($default);
$my_model->query('....');
Model::setDatabaseAdapter($another_adapter);
$my_other_model->query('....');
Model::setDatabaseAdapter($default);
which is awfully alike:
mysql_select_db('default_db');
mysql_query('...');
mysql_select_db('other_db');
mysql_query('...');
mysql_select_db('default_db');

Categories