Design patterns for making old php code object oriented - php

New to php .I'm working on an old code in which I have to add many new features.
The code doesn't use any object oriented features of php5 right now but I'll be using them and will try to refactor important and complex old stuff in free time.
I've couple of questions :
1. Being someone coming from java background,ability to access outside functions from within a class seems so wrong which I have to do in order to reuse old functions. Is this a right thing to do ?... feels so unnatural to me, is there any better way to reuse old functions ?
2. Can someone suggest some good design patterns that can be used with old php code to make it little object oriented and make it elegantly work with new features.

Being someone coming from java background,ability to access outside functions from within a class seems so wrong which I have to do in order to reuse old functions
This has always irked me about Java.
There is nothing wrong whatsoever with free functions. The mantra that "everything must be in an object in OOP" is complete rubbish; only things that logically fit inside object types should be so.
So don't worry about it at all.
Can someone suggest some good design patterns that can be used with old php code to make it little object oriented and make it elegantly work with new features.
No design pattern is going to do your refactoring for you.
Design patterns are not magic bullets; the phrase is horribly over-used, and is merely a way to describe oft-used design conventions. Browse through a list of patterns on Wikipedia if you really want, but instead I'd just write your code in the most logical way and if, afterwards, you notice that it happens to conform to someone's idea of a "design pattern" then... well, good for you I guess!

Here are my thoughts:
Unless you have a lot of testing that can ensure that you don't break everything while you refactor your code to utilize an Object Oriented design, I wouldn't recommend changing the way the existing code works. You can accomplish this by wrapping the old functions into logical groupings through the creation of Facade classes that either pass through the functionality to your existing code, or call several of the functions in your existing code if a more complex operation is needed. Your new code would consist of objects that interact with the legacy Facade as needed, and implement the new functionality using proper OO design.
One thing I think is necessary if you are planning to refactor the old code, is to have proper testing in place. I would take a look at SimpleTest if you don't already have proper testing. As far as design patterns go, it would depend heavily on the goals your existing code is trying to accomplish.

You can simply encapsulate the call of this functions in objects implementing particular interfaces
Refer to 1. This is a general rule; just identify some logic "modules" that are currently implemented through different functions and encapsulate and hide this functions behind objects and interfaces.

You could encapsulate access to the old code using the facade pattern to give you a clean interface between your code and the old code.
I have done this quite succesfully with legacy code that was quite badly written (mine, I'm ashamed to say!), were rewriting was not an option.
I finished with a nice clean interface which could be modified easily and was easy to read. It was well worth the extra effort and allowed me to refactor the old code at my leisure as and when time permits (still working on that).

I an idea more than anything.
If in Java you have ever made a static method such as MyClass::someStaticMethod( parameter ) then it's like using a 'free' function.
That's what static methods are really. They're accessible globally and all it really is is a really long name, but otherwise it's a free method.
You might have put them in a 'class' but really it's java's way of creating global functions in a limited sense. If you think about it this way, php free functions don't seem so bad since their names are shorter.

Related

I have been writing PHP without "classes" for years... what am I missing?

For the life of me, I can't seem to wrap my head around "classes" in PHP.
I have managed to write large, scalable, and popular websites without them.
What am I missing? (And how do I learn?)
Classes will help with code re-use and potentially a very structured application.
Procedural programming can be a lot faster in both development time and execution speed.
OO programming is the more mainstream way but not always the best way. Theres a book called PHP Objects, Patterns and Practice which is a very good read, it covers the basics of classes, why and how to use, abstraction and common design patterns such as MVC. It also covers unit testing and other very good practices for php developers
The point of classes (object oriented programming) is that it bundles data together with the code that operates on it. If done well, this leads to less tightly coupled and thus more maintainable code.
In practice it means fewer global variables (whether used directly or accessed through static factory methods) and lesss passing around of data (i.e. smaller method signatures).
For a concrete example, look at the Mysqli extension: each function has a procedural and an OOP version, and the procedural version nearly always needs to have an extra "link" parameter to give it context, wheras the OOP version gets that context from the current object.
Everybody answered was right you are missing a lot because let's say you have a photo gallery website
instead of writing functions and in the end you end with a lot of them
OOP would be useful in:
Code organization and maintainability
Adds clarity, and reduce complexity
Emphasizes data over procedures
Code modularity
Code re-usability (Believe me you will need that a lot)
Well-suited for databases
I wasn't using OOP before but i started and to be honest not very long time ago, and found it very useful in those points specially in the re-usability of the code
Let's say i have a photo gallery website
i will create a class for users and this class will do CRUD on all of the users table
and a class for the photos to do the CRUD on all of the photographs table
I could also make a class to do all the CRUD for me without specifying on what table
and then use the inheritance to extend all the CRUD in my users class and my photograph class
the point in that is i could only write the CRUD methods once
and then re-use it in all of my other classes
I hope i would have answered your question
IMO, If you do not wish to seperate your htmls & php code; you better not use classes.
You'll need them in a framework environment (not necessarily), and you'll need them if you want to objectify your datas, handle them like that.
but if you're fine without it, then you're just fine :)
When it comes to handle a very complex system, with a lot of different data structures, more than one team members, etc. You and your code need to be organized very well, and you'll need classes.
Good question! You got my upvote!
Straight to the point:
You're missing a whole world!
There are many metaphors to describe it but there's nothing better than practice - you obviously know it after "years" of programming!
Decide on a small project and write it OOP style. Then you'll get the idea.
Take this tip as well: Name your classes as their file names (ex. "MyClass" -> "MyClass.php"). Easy to maintain.
You are probably missing testability: I guess your functions call other functions, which in turn might call another function, right? So you will have trouble testing an isolated function. With OOP you assemble "heaps" of objects and can interchange each object with a "fake" one (called mock or stub) for a test. This way, you can test each functionality in isolation. Think of being able to test you output code without needing a database. Think of testing your controller code (the code which processes the request parameters and decides what action to take) without needing a web server.

Is it acceptable to wrap PHP library functions solely to change the names?

I'm going to be starting a fairly large PHP application this summer, on which I'll be the sole developer (so I don't have any coding conventions to conform to aside from my own).
PHP 5.3 is a decent language IMO, despite the stupid namespace token. But one thing that has always bothered me about it is the standard library and its lack of a naming convention.
So I'm curious, would it be seriously bad practice to wrap some of the most common standard library functions in my own functions/classes to make the names a little better? I suppose it could also add or modify some functionality in some cases, although at the moment I don't have any examples (I figure I will find ways to make them OO or make them work a little differently while I am working).
If you saw a PHP developer do this, would you think "Man, this is one shoddy developer?"
Additionally, I don't know much (or anything) about if/how PHP is optimized, and I know that usually PHP performace doesn't matter. But would doing something like this have a noticeable impact on the performance of my application?
You might be the only developer now but will someone else ever pick up this code? If so you really should stick mainly to the standard library names if you're doing nothing more than simply wrapping the call.
I've worked with code where the author has wrapped calls like this and it really does harm the ability to quickly understand the code
If you saw a PHP developer do this, would you think "Man, this is one shoddy developer?"
Well no...but I'd think "Damn...I've got to learn this guys new naming standard which although well-intentioned will take me time"
I assume you are referring not only to naming conventions, but also to the merry mixture of function (needle, haystack) and function(haystack, needle) parameter orders.
I can totally understand the desire to build sane wrappers around these in self-defense. I still rather wouldn't do it, though, simply because it adds a proprietary layer to your project that will make it harder to understand for others. Everybody knows what array_push does, but MyArrayFunctions::push one may have to look up, or even look into to find out what it does.
I tend to stick with the standards, even though they're admittedly crappy in this case. Plus, with a decent IDE that can look up functions and parameters as you type, the problem is already much reduced.
On the other hand, I can't really see any harm in, say, a static class Array that brings all the push(), pop(), array_this() and array_that() into one standard form. I'd say it's up to you, really.
Simple wrappers wont hit your performance, but this might confuse any future developers on the project. As a PHP programmer you slowly come to expect the weird naming conventions.
If you are adding any functionality its great to have consistent conventions. I have worked with a PHP static class that did wrap the native array functions (and add new ones). It was quite convenient to always have the same argument placements.
In my opinion OOP implementations of for example an array are okay, you will wrap them and partially modify functionality, however just renaming functions and shuffling arguments I don't like.
If you really need to do it make sure you comment it with phpdoc so people can see the correct syntax in the autocomplete of their IDE.

Utilities file in php?

What is the best way to deal with "utility" functions in a OOP PHP framework? Right now, we just have a file with several functions that are needed throughout the system. (For example, a distribute() function which accepts a value and an array, and returns an array with the value distributed in the same proportions and same keys as the input array.)
I have always felt "dirty" using that because it's not object-oriented at all. Is it better practice to move these into various classes as static methods, or is that just a semantic workaround? Or is there just going to be a level in a framework where some stuff is going to fall outside of the OOP structure?
I tend to make a Util() class that contains only static methods, has no attributes, and is not inherited from. Essentially, it acts as a "namespace" to a bunch of utility functions. I will allow this class to grow in size, but will occasionally split of methods into their own classes if it is clear that those methods are designed only to work with certain kinds of data or if it is clear that a group of related methods should be grouped into a class along with, perhaps, some attributes.
I think it's perfectly OK to deviate from purely OOP practices so long as the code that deviates is well-organized and is not creating architectural flaws in your system that make it harder to understand and maintain.
I've always been more pragmatic about questions like these.
If you want to go full-OOP, you should obviously stick these into classes. However, these classes are only going to be container classes, because they don't really represent objects of any kind.
Also: using classes would require you to either have an instance of that class, using the singleton pattern or declaring every function static. The first one is slower (okay, might not be that much, but in a large framework things like that get large, too - especially in interpreted languages like PHP), while the second and third ones are just plain useless and simply an OOP wrapper for a set of functions (especially the third approach).
EDIT: Feel free to prove me wrong. I might be. I'm not too experienced and always saw it that way, but I might be wrong.
I always think of utility functions as extensions of the standard php functions. They are not object oriented because you don't really get any benefit from making them OO.

Simple DB Model

I do not have much experience using frameworks or anything so that leaves me with little experience using Models (MVC). I have no interest whatsoever in using a framework at the moment. I am working on a website and I am trying to model some objects but I'm not sure exactly how I should be designing the class.
For instance, right now I have a class with a few public members which can be accessed directly. I have started prototyping some functions (select, delete, update) but I am not sure
If these functions should be static
If these functions should accept parameters or use the class members instead
If these functions should even exist how they do currently
If the entire concept I'm going for is the right thing to do
I can't seem to find any sort of hints on the interwebs as to how to create a model class.
If you're using a factory class then all verbs are usually instance methods and the factory is instantiated with some sort of DB session.
If the verbs are member's of the entity's class select is usually a static method while update is usually an instance method and delete is usually defined both ways (IE: delete(recordID) and entity.delete())
The entire concept is the right thing to do but you're going to do it wrong. Period. Making a scalable model like this takes a lot more time and effort than people have at their disposal. I know you have no interest in using a framework but you should.
My inference from your question is that this is a low profile project, and you have enough flexibility from your boss/client/teacher that you can build it however you want. That in mind, here is what I would think about when working on this.
If MVC is a new concept to you, then Test-Driven Development is almost certainly and alien one as well. However, I first cracked into a real understanding of OOP while doing it, so I suggest you give it a try. Writing some simple unit tests first against your model classes will take you through the exercise of figuring out how those model classes are going to be used. You'll be working with the external API of each of those objects (or groups of objects if you're not a TDD purist), and that will help guide the design of the internals. Check out PHPUnit for getting started, as the documentation has some great examples as well.
I think the TDD approach will lead you to the following conclusions:
Probably not. Static data/methods are usually only useful when you absolutely need one copy of something. I find in web apps that aside from maybe a resource connection like the DB this is rarely the case.
This depends on what the function does. Keep in mind that using local variables implies side-effects, or changes in the state of the object. If the data you need to operate on should not change the state of the entire object, use a parameter and return a value. It's also easier to test these kinds of methods.
Again, writing tests for these functions that illustrate how you'll use them in the application will lead you to a conclusion one way or another about whether you need them or whether they are designed correctly. Don't be afraid to change them.
Absolutely. How else are you going to become comfortable with MVC if you don't roll your own implementation at least once? In fact, it's probably better to grasp the concepts with real experience before you move to a more professional framework. That way, you'll understand why the concepts and conventions of the framework are the way they are.
Oh, and the lack of clarity that you're finding on what a model class is, is probably due to the fact that it's the part of your application that is most customized. This is your data model and domain logic, so a lot of it is case-specific. The best resource, though, IMHO is Martin Fowler, whose excellent book Patterns of Enterprise Application Architecture goes into a lot of detail on how and why to design a particular set of "model" classes with one pattern or another. Here is the online pattern library--obviously the book is more detailed.
Hope that helps somewhat.
When using PHP, I think designing object oriented model adds extra work with little benefits - even when looking on large frameworks, it's common to just use assoc-arrays that you can get from resultsets (see f.ex. the multiparadigm approach of Zend MVC).
While Object-Relational mapping is much more established among strongly typed languages like Java, there are already tools for PHP as well (f.ex. Doctrine). You may check it out if having OO-oriented model is what you want, but be aware that OR-mapping has severe issues of it's own and might be of little use in PHP (haven't tried it myself in a dynamic language yet).
For most newly started project, picking a good framework is usually a way to go - it can save you time and promote best practices (of course after some learning time that's different for every tool out there). When using some framework, you should always try to find out the framework's / community approach to solving specific problems (like model design & data access) before experimenting on your own.
The "correct" way to abstract away data access using object-oriented concepts is a hot-button topic for a lot of people. Put another way, there are several ways to do it and there is no "one right" way.
Rolling your own works best if you are seriously upgrading an existing application. This is because you have a heap of code that is already database dependant and you have some bounds for the necessary refactoring. It also teaches you about abstracting code because a lot of refactoring involves removing (or reducing) code duplication. Once you've done this to completion, you will have a much better idea of how a data model layer should work. Or at least, should work for the way you program. And you will know what not to do next time you build one. :-)
If you're starting a new codebase and haven't worked with a framework or object layer but know you need to build one, then the best advice I can give is to be willing to build one later, and refactor the code to suit when that does happen. Yes, it will likely mean your application will get 90% rewritten a few times.
Writing an object abstraction layer is difficult and you will end up with dense code that is fairly defensive about things, and doesn't take chances. But once you've got it working, you will also know how to build robust code, because it will probably be debugged fairly thoroughly.
No because, static methods are hard to test
It depends of the parameter, life cycle, etc. Impossible to answer without seeing some code.
?
No
OOP requires at least 10 years of experience to have a better view on what is wrong/right/better/worse.
So, if you are not a OOP expert, instead of losing too much time reinventing the wheel, I would suggest:
Use a well-known framework for the technical part
Create your classes/framework for the business/functional part.
(1) Will help you be ready in no time for the classic technical part (Session, database interaction, etc.). Will avoid you to make errors others already did.
(2) This is your core business, it should be "your DNA".
Also, using a well-known/good technical framework will make you read quality code and help you progress. (Be carefull some frameworks are really of poor quality)
When you will have enough experience, you will be able to skip the technical framework part and build/customize your own... because technical framework are usually evil (They serve too many purposes). :)

CLOS like object model for PHP

I have returned to php development from Moose and I really miss CLOS like object model for php. Is there some kind of syntaxtic sugar which would allow me to write less code in php when dealing with objects?
Just to stress this requirement a bit more. I don't want to write one thing in several places. I can live with part of code being generated automatically, but in the code that I have to see to develop I don't want to see redundant information which is just clutter (think: LISP macro if you really need more analogy). So this part can be also called DSL if that makes more sense.
I would love to have at least roles (mixins), and some kind of introspection without re-inventing the weel. Code generators and auto-loaders might be one way to solve at least part of this problem.
p.s. For JavaScript there is Joose, so similar API would be very useful.
There are no mixins in php yet but there is an RFC for traits which will work roughly the same. http://wiki.php.net/rfc/traits
Using overloading for __call can allow you to dispatch methods to other classes and have it look like a mixin.
The Symfony project has a mechanism for mixins, allowing aspect oriented programming like in CLOS. Personally, I don't like this kind of hacking in userland spacee (At least not with PHP). I think you would be better off using the features that the language provides, and perhaps wait for something like traits to (maybe) make its way into the language.
There is also new project http://github.com/huberry/phuby which implements roles in php!

Categories