I am using PHP 5.2.14 at work, so there is no namespace option for me.
Is it acceptable for me to substitute classes with static functions for namespacing?
For example, we have lots of "handy" function lying around that does miscellaneous things that are all bunched into this one file, and they tend to get messy.
I would love to see them follow some sort of organizing logic.
So my solution is this...
I want to just create classes called "StringTools" or "DateTools" and every time we need to do use those function I would simply call SomethingTools::funciton_name(...). It would be simple class filled with static functions, with an empty constructor, made purely for the sake of namespacing and organizing.
It would be easy to manage and very organized, because related functions will be organized into it's own file or even folder, the class calls will be handled by autoload, so we don't even have to include anything.
Is this an acceptable approach to the problem? or is there a better way to deal with organizing functions in pre 5.3 PHP so programmers doesn't step on each others feet when naming them? unorganized stuff really really bugs me and I'm actually looking forward to the hours of extra work I'll be spending sorting this out.
This is not just acceptable its probably the only clean solution. The goal of an object should always be to group like functions, so as long as you are following this, it would make sense (IMO) to group these functions into classes. What you want to watch out for is that you actually grouping like functions and not just throwing functions into a class. This will just make the problem worse as it will confuse developers when it comes to finding methods when writing new code.
Related
I designed a PHP 5.5+ framework comprised of more than 750 different classes to make both web applications and websites.
I would like to, ideally, be able to reduce its size by producing a version of itself containing just the bare essential files and resources needed for a given project (whether it's a website or a web application).
What I want to do is to be able to:
reduce the amount of traits, classes, constants and functions to the bare essential per project
compress the code files to achieve a lesser deployment size and faster execution (if possible)
So far, I've got the second part completed. But the most important part is the first, and that's where I'm having problems. I have a function making use of get_declared_classes() and get_declared_traits(), get_defined_constants() and get_defined_functions() to get the full list of user-defined classes, traits, functions and constants. But it gives me pretty much EVERYTHING and that's not what I want.
Is there a way to get all defined classes, functions and constants (no need for traits as I could run class_uses() on every class and get the list of traits in use by that class) for a single given script?
I know there's the token_get_all() function but I tried it with no luck (or maybe it's I'm using it the wrong way).
Any hint? Any help would be greatly appreciated :)
You can use PHP Parser for this. It constructs abstract syntax trees based on the files you supply to it. Then you can analyze its output for each file, and produce a report usable to you.
Other than that, you can use token_get_all() approach you've mentioned already, and write a small parser yourself. Depending on your project, this might be easier or more difficult. For example, do you use a lot of new X() constructs, or do you tend to pass dependencies via constructors?
Unfortunately, these are about the only viable choices you have, since PHP is dynamically typed language.
If you use dependency injection, however, you might want to take a look at your DI framework's internal cache files, which often contain such dependency maps. If you don't use such framework, I recommend to start doing this, especially since your project is big and that's where dependency injection excels at. PHP-DI, one of such frameworks, proved to be successful in some of my middle-size projects (25k SLOC).
Who knows? Maybe refactoring your project to use DI will let you accomplish the task you want without even getting to know all the dependencies. One thing I'm sure of is that it will help you maintain it.
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.
This question already has answers here:
Classes. What's the point?
(12 answers)
Closed 9 years ago.
if i have a collection of useful functions in a file called functions.php (easy enough)
what would be the advantage of OOP?
I want to learn it, but its pretty in depth so before I dive it, would be nice to know if there is an advantage. I can send variables to the functions just as easily as I can receive them.
example i have
functions del_some_string($x,$y)// made up function to delete y number of letters from $x
why would this be better as a OOP?
Depends on what the functions do, if you have some common data on which you do various operations to manipulate the same data you might want to model it in a class. On the other hand if all data you are working with has no relation with each other there is not really a benefit of using OOP.
For example the function you mentioned is more a utility function than a member of a class.
I've been using PHP for roughly 10 years now. I can't count how many times I've run across "functions.php" or "library.inc.php" or one of its many equivalents.
It's a bad idea. Don't do it. If you find yourselfs writing files like that, stop it. NOW.
It's not a matter of OOP vs functional programming. It's a matter of organising your code. Group your functions and variables properly and OOP will feel natural. If your functions do many things and don't lend themselves easily to being grouped, try to refactor them so they only do ONE thing at a time. You'll find that this also lets you strip a lot of redudancy out of your existing functions.
You can use OOP to encapsulate your code further: put your variables into objects and have the functions that operate on these variables either be property methods of those objects or interact with these objects as input. Avoid "global" and don't modify your function arguments routinely.
Your problems aren't the problems you think you have.
EDIT: As for your example: since strings aren't objects in PHP, you can't really put that function in a sensible class, so you'd probably want to put it into a utility module with other string functions and use it as you already do. Still, tearing apart your functions.php and turning it into a collection of atomic modules does wonders to your code's readability. You may find a file containing assorted functions readable because you are familiar with its contents, but another coder (and "you after three months of not using the code" IS another coder) will not.
EDIT2: Please understand that "OOP" doesn't magically make everything better. It's a tool that is supposed to help you writing better code. If you use OOP everywhere, you're probably doing it wrong (or writing for Java *cough*). If you use OOP without understanding things like structured code first, you won't get anything out of it, either.
It wouldn't. It's not a matter of better or worse. It's the paradigm that's important.
All computer programs aim to solve a problem. You can use Imperative Programming or you can use OOP (among others) to solve this problem. OOP will just change how you structure and organize your application, because it embraces concepts like encapsulation, polymorphism, and inheritance (to name some). These are not generally available in imperative programming, but that doesn't mean imperative is worse. It's just different.
If you are coding PHP, you can use either or. PHP is not a strictly object-oriented language. However, as of PHP5, there is an increased focus on OOP. New additions to the API are almost always Classes now (SPL, DateTime, Internationalization). If you want to use those, you definitely should look into OOP.
OOP goes much further then just calling functions.
Classes collect functions that operate on the same set of data or share the same goal. But another advantages of classes taking DRY to the next level. With functions, you can encapsulate some simple task so you don't have to repeat that over and over. With OOP, you can encapsulate more complex tasks so you won't have to repeat that.
If you tend to pass the same sort of data to several functions sequentially, you can think about using a class, and pass that data to the constructor and saving it in the class. That way, you can call the functions without having to pass that data each time.
You can instance of a PHP class and use it's all combined properties and methods. You can manipulate an object during the execution of the script, and state is saved.
class Myclass{
public $a, $b, $c;
public setA(){
$this->a = b;
}
public getA(){
return $this->a;
}
}
this is what you cant do with a function:
$x = new Myclass;
$x->setA();
print $this->getA();
you can't simulate the same functionality with a functions PHP. You run your functions one time, and since there is no instance, you have to hold these variables somewhere else. If you write a big aplication, this functions.php will be a big black hole. If you use seperated classes with it's functionality-aimed properties and methods, you can extend your PHP application as much as you want. If you don't use OOP, you can never setup a framework. but you will understand the importance of OOP, when you have to write something huge.
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.