Open / Closed principle - How to call the new versions? - php

I'm trying to grasp the Open/Closed principle (in my case for PHP, but that shouln't really make a difference).
The way i understand it is that a class is never open for modification. Only for bug fixing. If i wanted to add new code to the class, then i'd have to create a new one and extend the 'old' class. That's the only way i can add new code to it.
In a way i can see the advantages of this. Because basically you create some sort of versioning system, where old code always work, but you can always try to use the new classes too.
But how does this work in practice? I mean, suppose i have the following class:
class MyObject
{
public function doSomething()
{
echo 'Im doing something';
}
}
So somewhere i'm probably instantiating this class:
$obj = new MyObject();
But then i decide that it's good to have another method in that object. So i can do something else too. According to the OCP i can't modify the class. So i have to create a new one, which extends to old one right?
First problem. How do i call the new class? Because it isn't really a complete new object. Like. a User object is a User object. I can't suddenly give it completely diffent name just because it needs another method. Anyway, i create the new class:
class MyNewObject extends MyObject
{
public function doSomethingElse()
{
echo 'Im doing something else now';
}
}
Now this also means i have to change the line of code where i instantiated the "MyObject" class and replace it with the "MyNewObject" class, right..? And if that's done in more than one place, then i have to search through my source code... (Think about a method in a controller class, which almost always uses the 'new' keyword to instantiate certain classes).
The same basically applies to inheritance. I'd have to find each class the inherits the old class and have to replace that with the new class.
So basically my questions are:
How do you name the new classes which have the new methods? Just becasue i added some new functionality, doesn't mean i can give the class a whole new name...
And what if the 'old' classs is instantiated (or inherited) from multiple places. Then i'd have to find all of those places... Where's the gain?

The Open Closed Principle isn't intended to be used as a kind of version control system. If you really need to make changes to the class, then go ahead and make those changes. You don't need to create new classes and change all the places that instantiated the old one.
The point of the Open Closed Principle is that a well-designed system shouldn't require you to change existing functionality in order to add new functionality. If you are adding a new class to the system, you shouldn't need to search through all your code to find the places where you need to reference that class or have special cases for it.
If the design of your class isn't flexible enough to handle some new piece of functionality, then by all means change the code in your class. But when you change the code, make it flexible so you can handle similar changes in the future without code changes. It's meant to be a design policy not a set of handcuffs to prevent you from making changes. With good design decisions, over time your existing code will require fewer and fewer changes when you add new functionality to the system. It's an iterative process.

I would argue that by adding a function, you're not modifying the class behavior.
In all the instances where doSomething() is currently being called in your app, simply by adding doSomethingElse() to the class will have no effect. Since you're not changing doSomething(), the behavior is the same as it was before.
Once you determine that your doSomething() implementation isn't cutting it for certain circumstances, you can extend the class and override doSometing(). Again, the original still behaves the same as it always did, but now you have a new doSomething() to work with also.
I realize that this goes against the strict definition of open/closed, but this is the real world, and that's how I interpreted that principle in my code.

You need to create a constructor in your MyNewObject class which calls the parent class' constructor:
function __construct() {
parent::__construct();
}
This way you can instantiate the new class and still access all the functionality of the extended one.
You can then also override any function in the parent class (as long as it is not marked final of course).
So you could do:
$newObj = new MyNewObject();
$newObj->doSomething();
$newObj->doSomethingElse();

Related

PHP Access Class from Another class with Initializer

Ok, so I am building a web application relying on Zend PHP....
Before having to read everything to describe my nested functions, what I need is to be able to call a function from one class to another, which neither are extended upon another, are already extending a db constructor, which are all independently separate files called by one master initializing script .... (?) ... Thanks in advance, and there is a better example below as to what I mean.
My HTML Page calls a "master" include list which initializes and creates all the instances of all my classes so that all pages have common access to the functions. i.e. require('app_init.php');
Here is the most important excerpt of app_init.php:
require_once('class-general.php');
require_once('class-users.php');
require_once('class-identities.php');
$general = new General();
$users = new Users($db);
$iden = new Iden($db);
---class-general.php
$general is my basis for stupid common functions I use, as well as the DB constructor that all classes can be extended from.
----class-users.php
<?php
class Users extends General{
public function getUserID(){....random block of auth code.... return $randomID#; }
}?>
-----class-identities.php
<?php
class Iden extends General{
public function do_random_change_to_db($with_me){
....random prepared function using $with_me....
$this->logger->log("Someone with UserID: ". /*((?$this?) HERE:)*/ FIXME->getUserID() . " did something : ".$with_me ."." , Zend_Log::INFO);
$success="gucci";
return $success;
}
}?>
Right now, I am being tossed a PHP error for
Fatal error: Call to undefined method Iden::getUserID() in ...`
What would be the best way to go about this? I've tried to include one class file with the other one, but i dont exactly want to create a $FIXME= new Users(); either to save on memory space.
I also honestly would prefer to not extend any more classes off another at this time.
Thank you in advance.
If the getUserID method does not depend on any instance state (and it doesn't look like it does, though you haven't made it entirely clear), making it static will allow you to call it like so:
Users::getUserID();
If it does depend on instance state, you will need to call it on an instance of the Users class.
It seems to me that General's methods should actually be static as well, or perhaps even be free functions outside of a class. Remember: classes are used to encapsulate state. If there's no state that needs to be encapsulated, use class (static) methods or simple functions. Do not needlessly complicate your code by introducing objects and inheritance in which those paradigms don't make sense.

Does this break open closed principle

I am attempting to create a factory. I want the client to send a code to the create method, which will be used to instantiate a class that is used to process that type of 'thing'.
The list of codes are a member of the class, since they should never change. But, to make it more testable i have added a setter for the codeMap array.
Does this break the open closed principle and if so, how to make this testable correctly?
<?php
class My_ThingFactory
{
/**
* #var array
*/
private $codeMap = array(
'A111' => 'My_Thing_ConcreteA'
);
public function create($code)
{
if (isset($this->codeMap[$code])) {
return new $this->codeMap[$code];
}
}
public function setCodeMap(array $codeMap)
{
$this->codeMap = $codeMap;
}
}
The Open/Closed principle has to do with extending some code to add functionality without modifying the core behavior (i.e. by not editing the source code) of your class. Your class keeps its internals to itself and provides clear public interfaces to interact with them. From this perspective, no you have not broken open/closed principle. At least not at face value.
However, that said, I also got the impression from your question that you are wondering if having a setter for your private $codeMap array breaks the principle. It doesn't directly, but the implementation also makes it attractive to modify if another developer wants more fine tuned access to the $codeMap array. Basically, the only way to update this array on the fly is to wipe it out and reset it with setCodeMap(). You are not providing a mechanism to add a single code to the map. As soon as you find yourself needing more granular access to this map, you will also find yourself violating the open/closed principle.
Consider this, let's say another developer is using your code and the $codeMap array is 20 or 30 elements strong; they must hack your core code to provide better access to that array. Since there is not way to add a single code, they must create a new array to pass to setCodeMap() that consists of the current $codeMap array plus any additional elements they wish to add. There isn't another way (besides hardcoding the original array) to do this without opening up the My_ThingFactory and adding something like:
public function getCodeMap()
{
return $this->codeMap;
}
Then in their extended class they could do something like:
class AnotherThingFactory extends My_ThingFactory
{
public function addCodes(array $newCodes)
{
$this->setCodeMap(array_merge($this->getCodeMap(), $newCodes));
}
}
But again, this is only possible by going into your class and adding the needed functionality before, which does break the open/closed principle. You could also rectify this by simply making the $codeMap property protected and then an extending class can do what they need to without hacking your code. The extending class also then has the onus of ensuring that they are manipulating it correctly.
So to answer the open/closed question: if you are intending to keep the $codeMap locked down by design and don't intend for it to be used in alternate way then you are fine. But as I said above as soon as you need better control of the $codeMap array, you will need to violate the principle to do so. My suggestion would be to brainstorm how much management of that factory you want built in to your class and make it part of the class core functionality.
As for testing, I don't see why you couldn't test this code as it is. You can set your code map and then test for the corresponding instance that was returned with the create() method.
class FactoryTest extends PHPUnit_Framework_TestCase
{
private $factory;
public function setUp()
{
$this->factory = new My_ThingFactory();
}
public function tearDown()
{
$this->factory = null;
}
public function testMadeConcreteA()
{
$this->assertInstanceOf('My_Thing_ConcreteA', $this->factory->create('A111'));
}
public function testMadeStealthBomber()
{
$this->factory->setCodeMap(array('B-52', 'StealthBomber')); //Assume the class exists.
$this->assertInstanceOf('StealthBomber', $this->factory->create('B-52'));
}
public function testDidntMakeSquat()
{
$this->assertNotInstanceOf('My_Thing_ConcreteA', $this->factory->create('Nada'));
}
}
The open-closed principle is not universal. You need to make an assumption about what is likely to change (the open part) and what is not (the closed part).
Since you're using a factory, the closed part is the create service (factories make this part closed). The open part is the things the factory is going to create. A factory allows extending those things later.
A small but important point is that your pattern is not a GoF factory, but rather a Simple Factory. So, it's perhaps not the strongest form of Factory for exploiting the open-closed principle. That is, if you add new stuff to create, you have to modify the class (the $codeMap array).
What stands out in your question is that you seem to contradict the principle of openness when you say:
The list of codes are a member of the class, since they should never change.
In my mind, if you're using a factory, the list of codes is expected to change.
As for your set function, it's a public method, and so by definition is closed (else you shouldn't reveal it). On the other hand, you're exposing details of the implementation (as mentioned in Crackertastic's answer). You might be concerned more about violating encapsulation with this method.
I think an easier solution (although I'm not sure about it in PHP) is to initialize your factory with a $codeArray that's been created by another class. I think this is what Kamal Wickamanayake refers to in his comment on your question. Another solution is a service (closed) to add/delete elements (which boil down to adding new entries into your $codeArray but in a hidden way).

Should I remove static function from my code?

My code is located here: https://github.com/maniator/SmallFry
Should I make it so that that the App class does not have to use static functions but at the same time be able to set and set variables for the app from anywhere?
Or should I keep it how it is now with App::get and App::set methods?
What are the advantages and disadvantages of both?
How would I accomplish that 1st task if I was to undertake it?
Related Question
Sample code:
//DEFAULT TEMPLATE
App::set('APP_NAME', 'SmallVC');
//END DEFAULT TEMPLAT
//
//DEFAULT TEMPLATE
App::set('DEFAULT_TEMPLATE', 'default');
//END DEFAULT TEMPLATE
//DEFAULT TITLE
App::set('DEFAULT_TITLE', 'Small-VC');
//END DEFAULT TITLE
//LOGIN SEED
App::set('LOGIN_SEED', "lijfg98u5;jfd7hyf");
//END LOGIN SEED
App::set('DEFAULT_CONTROLLER', 'AppController');
if(App::get('view')){
$template_file = $cwd.'/../view/'.App::get('view').'/'.App::get('method').'.stp';
if(is_file($template_file)){
include $template_file;
}
else {
include $cwd.'/../view/missingview.stp'; //no such view error
}
}
else {
App::set('template', 'blank');
include $cwd.'/../view/missingfunction.stp'; //no such function error
}
I think you have a feeling that static is bad. What I am posting may seem fairly crazy as it is a massive change. At the very least hopefully it presents a different idea of the world.
Miško Hevery wrote static methods are a death to testability.
I like testing, so for that reason I don't use them. So, how else can we solve the problem? I like to solve it using what I think is a type of dependency injection. Martin Fowler has a good but complicated article on it here.
For each object at construction I pass the objects that are required for them to operate. From your code I would make AppController become:
class AppController
{
protected $setup;
public function __construct(array $setup = array())
{
$setup += array('App' => NULL, 'Database' => NULL);
if (!$setup['App'] instanceof App)
{
if (NULL !== $setup['App'])
{
throw new InvalidArgumentException('Not an App.');
}
$setup['App'] = new App();
}
// Same for Database.
// Avoid doing any more in the constructor if possible.
$this->setup = $setup;
}
public function otherFunction()
{
echo $this->setup['App']->get('view');
}
}
The dependancies default to values that are most likely (your default constructions in the if statements). So, normally you don't need to pass a setup. However, when you are testing or want different functionality you can pass in mocks or different classes (that derive from the right base class). You can use interfaces as an option too.
Edit The more pure form of dependency injection involves further change. It requires that you pass always pass required objects rather than letting the class default one when the object isn't passed. I have been through a similar change in my codebase of +20K LOC. Having implemented it, I see many benefits to going the whole way. Objects encapsulation is greatly improved. It makes you feel like you have real objects rather than every bit of code relying on something else.
Throwing exceptions when you don't inject all of the dependencies causes you to fix things quickly. With a good system wide exception handler set with set_exception_handler in some bootstrap code you will easily see your exceptions and can fix each one quickly. The code then becomes simpler in the AppController with the check in the constructor becoming:
if (!$setup['App'] instanceof App)
{
throw new InvalidArgumentException('Not an App.');
}
With every class you then write all objects would be constructed upon initialisation. Also, with each construction of an object you would pass down the dependencies that are required (or let the default ones you provide) be instantiated. (You will notice when you forget to do this because you will have to rewrite your code to take out dependencies before you can test it.)
It seems like a lot of work, but the classes reflect the real world closer and testing becomes a breeze. You can also see the dependencies you have in your code easily in the constructor.
Well, if it was me, I would have the end goal of injecting the App dependency into any class (or class tree) that needs it. That way in testing or reusing the code you can inject whatever you want.
Note I said reuse there. That's because it's hard to re-use code that has static calls in it. That's because it's tied to the global state so you can't really "change" the state for a subrequest (or whatever you want to do).
Now, on to the question at hand. It appears that you have a legacy codebase, which will complicate things. The way I would approach it is as follows:
Create a non-static version of the app class (name it something different for now) that does nothing but proxy its get/set calls to the real app class. So, for example:
class AppProxy {
public function set($value) {
return App::set($value);
}
}
For now, all it has to do is proxy. Once we finish getting all the code talking to the proxy instead of the static app, we'll make it actually function. But until then, this will keep the application running. That way you can take your time implementing these steps and don't need to do it all in one big sweep.
Pick a main class (one that does a lot for the application, or is important) that you easily control the instantiation of. Preferably one that you instantiate in only one place (in the bootstrap is the easiest). Change that class to use Dependency Injection via the constructor to get the "appproxy".
a. Test this!
Pick another class tree to work on, based on what you think will be most important and easiest.
a. Test!!!
If you have more calls to App::, Go to #3
Change the existing App class to be non-static.
a. Test!!!!!!!!!!
Remove the AppProxy and replace with App in the dependency injectors. If you did it right, you should only have one place to change to make this switch.
Pat yourself on the back and go get a drink, cause you're done.
The reason that I segmented it out like this is that once a step is completed (any step), you can still ship working software. So this conversion could take literally months (depending on the size of your codebase) without interrupting business as usual...
Now, once you're done, you do get some significant benefits:
Easy to test since you can just create a new App object to inject (or mock it as needed).
Side effects are easier to see since the App object is required wherever it could be changed.
It's easier to componentize libraries this way since their side effects are localized/
It's easier to override (polymorphism) the core app class if it's injected than if it's static.
I could go on, but I think it's pretty easy to find resources on why statics are generally bad. So that's the approach I would use to migrate away from a static class to an instance...
If you don't want to have static functions but global access from everywhere WITHOUT passing the object to the places where it is actually needed then you pretty much can only use one thing:
A global variable
So you are not really better of doing that. But that is the only thing i can think of that would fulfill your requirements.
If you App object is something like an application config a first possible step would be to pass it to the objects that need it:
class Login {
public function __construct() {
$this->_login_seed = App::get('LOGIN_SEED');
self::$_ms = Database::getConnection();
}
changes into:
class Login {
public function __construct(App $app) {
$this->_login_seed = $app->get('LOGIN_SEED');
self::$_ms = Database::getConnection();
}

PHP OOP - Require or Extend

I was wondering if there is any major different in the following, and whether one is more 'standard' than the other:
<?php
class Account extends Database {
public function myMethod()
{
// Do something
}
}
?>
or
<?php
require('database.class.php');
class Account {
public function myMethod()
{
// Do something
}
}
?>
Cheers :)
Edit:
This question actually relates to a tutorial series I have been following which describes the above two methods - which didn't make any clear sense.
So thank you for the constructive answers on clearing that one up!
Those are two completely separate language constructs.
Your first example deals with inheritance. Basically, you already have a class called Database, but you want to have a specialized version of that class to handle accounts. Rather than build a brand new Account class and copy/paste all the functionality you already have in your Database class, you simply tell PHP that you want to use the existing Database class as a baseline. You create any account-specific functionality in the new Account class, and anything database-related comes automatically. This is assuming, of course, that you have some way of specifying where the Database class is defined - for example, a require declaration at the top of the class, or an __autoload() or spl_autoload_register() function call defining a way to find and locate the file containing the Database class.
In your second example, your database-related code is completely separated from your Account class. They're completely distinct entities, and if you wanted to do anything database-related in your Account class, you would have to explicitly instantiate a new Database object within that class (or pass it to that class, or one of its functions, as a parameter.
Basically, extends helps define what a class is, whereas require shows where a class definition (or other code) is stored.
Both code snippets aren't even equivalent.
The first declares Account to extend Database, a is-a relation.
In the second code snippet, you are simply saying that you require 'database.class.php' ... and that neither has anything to do with OO, nor defines a is-relation from Account to Database.
Both are completely different in first one class is inherited by another class but in the second one the class is included in your script only.
Means if you extend all the public and protected methods are available in your derived class and you can create object of derived class and can use methods with derived class's object.
But in the second method the class is included in your script and require this class it's own method and work independently.
The first means you create a new class, which has all the functionality of Database class and those you implement.
The second means that you create a new class, but it doesn't have Database functionality since it's not extending it. If you need database access in your Account class, you can create an instance in constructor, or pass already created instance as constructor parameter.
It's hard to say what is more standard, since it depends on what You actually want to achieve.
To put it in most simple terms:-
require or include is structural programming.
extends is object oriented

php extending classes

I'm using a salesforce class called SforceEnterpriseClient. I've referenced that class many places in my application. I want to extend that class to give it the ability to return a single array from a 1 row recordset, right now the record set is about 3 levels deep. There's a few other things I want to do with it as well. I can handle all that.
Everything I've read about classes says that when I extend a class, I need to call the new one as such:
class MySF extends SforceEnterpriseClient {};
$mySforceConnection = new $MySF;
That means in all of my existing code I have to find/replace.
Is it possible to overwrite the parent with the child so I don't have to play the find/replace game?
class SforceEnterpriseClient extends SforceEnterpriseClient {};
$mySforceConnection = new $SforceEnterpriseClient ;
You can probably play some classloading tricks with the magic __autoload() function and removing references to the salesforce file ie. require, require_once, include, include_once; But in the interest of readability and maintainability, you should probably take the long route here and modify all your references to use the subclass.
How about this, in the source file for the class, rename the class (and most likely the constructor as well) then extend the class using something like
class SforceEnterpriseClient extends renamedClass {};
Then rename the file and create a new file with the old name and include the renamed file. Put the code for your extended version in the new file. The final result is that every file that was using the original will see the new version without having to track them all down.
About the only major issue would be what happens when a new version of the class becomes available.
Unfortunately, that would be the only way to do so. You cannot reverse inhertiance. Sorry and good luck!
Kyle
Maybe you do not need to extend the class in this scenario. You extend a class when you want to add new functionality or change existing functionality AND keep the original class intact. Usually this is the way to go. But, if you need to make a change to an existing class and then update all references to the class to refer to the new class why not simply change the class code itself? That way the references would not have to change.
Also have a look at the factory pattern. Normally you should keep class creation and business logic separate.
So when you come across a problem like this, you only have to go and change the factory...
$sfEnterpriseClient = Factory::getSFEnterpriseClient($params);
that way you can avoid 'new' constructs in your business logic, and makes your code more manageable

Categories