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!
Related
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.
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.
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). :)
I have learned how to use classes in PHP and so far I have only really found one useful application for them. I created a user class to preform various tasks relating to users in my web application such as output the avatar, show number of messages ect.
Aside from this example, what are some other useful ways to utilize classes in a practical sense?
I use a database class all the time.
Here are a couple examples:
http://www.massless.org/_tests/phpdb/
http://slaout.linux62.org/php/index.html
http://www.tonymarston.net/php-mysql/databaseobjects.html
It's a really good idea to read other people's code and see how they have separated things into classes. Look at some PEAR modules or a framework ( Zend, Symfony, Cake ).
Any time you can define a 'thing' that 'does stuff', you've got a candidate for defining an object. Two concrete examples, from the PHP standard library, that immediately pop to mind are :
Numerous database modules use objects for connections, queries & results.
The DateTime class encapsulates a generic concept of time with input & output formatting, timezone conversions & date arithmetic.
The thing is, Object Oriented Programming is a big idea - you can solve almost any programming problem in an object oriented way.
I've built an utility class that humanizes the use of the mail() function, which I tend to use quite a lot.
By using classes (e.g. PEAR packages mentioned above, others), you are able to leverage code that has already been written and tested to perform common tasks.
Helps you to not reinvent the wheel, too.
I would highly recommend learning about [design patterns][1]. Many of them make good use of classes and solve common programming problems. In particular the Factory and Abstract Factory patterns are a good place to start.
There is also an excellent book called PHP Hacks that has a chapter about implementing a host of different patterns in PHP, so you might want to check that out.
Also, explore some of these built-in objects in PHP to see how they work and get more ideas:
PDO
ArrayObject
SimpleXMLElement
DirectoryIterator
[1]: http://en.wikipedia.org/wiki/Design_pattern_(computer_science)"design patterns"
I created a user class to preform various tasks relating to users in my web application such as output the avatar, show number of messages ect.
Check out http://en.wikipedia.org/wiki/Cohesion_(computer_science)
Your example sounds like Logical cohesion.
Aim for functional cohesion. Each class does a particular task, and make classes as generic as possible and you'll find you can reuse them over and over.
A great example of that, is Symfony's sfParameterHolder:
http://www.symfony-project.org/book/1_2/02-Exploring-Symfony-s-Code#chapter_02_sub_parameter_holders
Symfony uses it to hold variables for view templates (in a MVC), to store request parameters in the web request object (itself a class that represents all request parameters dutifully stripped of backslashes etc), in the sfUser class to store all the parameters that eventually go in the $_SESSION etc etc.
Download Symfony's "sandbox", go into the /lib/symfony/ folder and learn from it. It"s complex but the code imho is very clean.
http://www.symfony-project.org/installation
Zend is nice too, but the number of include files mayb be overwhelming and I am personally not fond of their naming conventions, in particular using underscore prefixes.
I'm just curious if any project exists that attempts to group all (or most) of PHP's built-in functions into a more object-oriented class hierarchy. For example, grouping all the string functions into a single String class, etc.
I realize this won't actually solve any problems (unless the modifications took place at the PHP source code level), since all the built-in functions would still be accessible in the global namespace, but it would certainly make usability much easier.
Way too many times. As soon as someone discovers that PHP has OO features they want to wrap everything in classes.
The point to the OO stuff in PHP is so that you can architect your solutions in whichever way you want. But wrapping the existing functions in Objects doesn't yield much payoff.
That being said PHP's core is quite object oriented already. Take a look at SPL.
I think something like this is intergral for PHP to move forward. Being mainly a .Net programmer, I find PHP painful to work in with it's 1 million and 1 global functions. It's nice that PHP 5.3 has namespaces, but it doesn't help things much when their own libraries aren't even object oriented, let alone employ namespaces. I don't mind PHP as a language so much, but their API is terribly disorganized, and it probably needs a complete overhaul. Kind of like what VB went through when it became VB.Net.
To Answer your question, Yes there exists several of libraries that do exactly what you are talking about. As far as which one you want to use is an entirely different question. PHPClasses and pear.org are good places to start looking for such libraries.
Update:
As the others have suggested SPL is a good library and wraps many of built in php functions. However there still are lots of php functions that it does not wrap. Leaving us still without a silver bullet.
In using frameworks such as Cakephp and Zend (others too), I have noticed that they attempt to solve some of these problems by including their own libraries and building basics such as DB connectivity into the frame work. So frameworks may be another solution
I don't agree. Object Oriented Programming is not inherently better than procedural programming. I believe that you should not use OO unless you need polymorphic behavior (inheritance, overriding methods, etc). Using objects as simple containers for code is not worth the overhead. This is particularly true of strings because their used so much (e.g. as array keys). Every application can usually benifit from some polymorphic features but usually at a high level. Would you ever want to extend a String class?
Also, a little history is necessary to understand PHP's odd function naming. PHP is grounded around The Standard C Library and POSIX standard and uses many of the same function names (strstr, getcwd, ldap_open, etc). This is actually a good thing because it minimizes the amount of language binding code, ensures that a full well thought out set of features (just about anything you can do in C you can do in PHP) and these system libraries are highly optimized (e.g. strchr is usually inlined which makes it about 10x faster).