Sharing functions across unrelated classes - php

I'm still working my head around object orientated programming and getting away from procedural programming. Although I use classes I know I still don't write my code fully OOP. I've been reading and doing my best to get as much information and practice as I can to further my abilities and I'm making progress, but one area that I'm currently confused on is how to deal with an independent function that would be reused across multiple classes that are entirely unrelated.
I understand I can extend classes, or implement an interface, or use a trait. I found this post, which was very helpful in clarifying things, however I'm still confused what is the correct method to use in this situation. For example, I have a function that will generate a random alphanumeric string to a length specified by an input, and will return that string. Several classes, not related, can use this function and it makes no sense to include the function in each class.
To me the most obvious thing is a library of common functions in a trait, which I can then just use in a class as needed. However is this the proper way to do things?

Yes, absolutely.
You don't need traits for utilities, just make a library. If you want to be tidy and stick to the object-oriented paradigm, create utility classes that group several static methods performing similar tasks - instead of creating large PHP files containing a bunch of functions that pollute the global scope.

For example, I have a function that will generate a random alphanumeric string to a length specified by an input, and will return that string. Several classes, not related, can use this function and it makes no sense to include the function in each class.
It's not a function. It's a responsibility. A good rule of thumb is to forget functions exist when doing OOP. Your function is a class RandomAlphanumericStringGenerator. It has one method generate that accepts $length as an input, which will generate and return the string. Create an instance of that Generator and inject it to objects that have need for this.

Related

Is there any difference between a global function and wrapping such function into a namespaced class?

Suppose you have a global method().
You can move it into a namespace and a class, and call it something like
\\Namespace\Class::method();
Is there any difference? Is one better than another?
Essentially you have not change anything and the method is for all intents and purposes just as global as it has been before - you can still call it from anywhere, but you have to type more characters. Did I miss something embarrassingly basic?
Namespaces and classes will not only help you with compartimentalization of your code and help you avoid name collissions, but actually make it faster by being able to use autoloaders and only load what you need when you need it.
It's very unlikely you'd call your method like this:
\\Namespace\Class::method();
You are much more likely to declare use Namespace\Class statements at the top of your file, and just do Class::method();.
And even more likely (and quite probably better) you'll actually instantiate a real object instead of using static methods (which are convenient, but can really break down encapsulation). In your example you are using an static method, which for a lot of people are not particularly object-orientedy.
Functionally, considered in isolation, there is no real difference between a method and a function. But a method has access to class properties and private methods, so it further helps you to build a system where responsibilities are properly distributed.
But to be meaningful, the difference has to be more than cosmetic. If you are using classes and objects, read on SOLID principles and design patterns (a bit at a time) and embrace the advantages of OOP.

Static methods or not?

I need to develop a small CMS using PHP, and right now I'm trying to figure out the structure.
The CMS will be generated using a set of functions. Things like database functions, caching thingies, internationalization and stuff like this.
I was thinking to do it like this:
make the functions non-static methods part of a big "site" class; that way I could run multiple instances of that class. Not sure I would need to do that though..
or split the functions into separate classes with static methods
The main problem here is that the CMS should be able to manage multiple small sites, not just one. So either I make all methods static and add a "site switch" function, or make them normal objects which I instantiate based on the site which I want to manage
Which of these would be the best option?
Static methods are generally bad practice. They introduce a lot of potential issues.
1) They introduce hidden dependencies. Code which arbitrarily calls foo::bar() has a dependency on foo and cannot run without foo being defined. The object using foo::bar() will construct correctly but won't be usable if foo is not defined.
2) Statics are globals. Global state is very bad, anything can change the code and its state is unknown. You sacrifice the power and control achieved by OOP encapsulation by using static methods.
3) It's impossible to substitute the functions for a different version
4) It makes unit testing impossible.
For more detailed information and code examples, see this article and this article
I'd definitely suggest using static classes for this job. Going this route will create a pseudo namespace for all of your functions so you don't have to worry about conflicting function names, etc, and it also prevents you from having to pass around an instance of your helper class just to call one of your helper functions.

I have a class with 14 static methods and 4 static properties - is that bad?

I have been writing a PHP class that is exactly 450 lines long and it contains 14 static methods and 4 static properties as well as 6 constants (and private __construct() and __clone()).
I am wondering here is that am I doing something wrong, is my class evil?
When you use the class, you always call a single method like:
MyClass::coolMethod();
and then you leave it alone altogether so it feels that it would be stupid to make it constructable?
There's really not much point in constructing objects out of it, because it is more like a tool that contains a few methods that you can just call directly.
Actually, out of those 14 methods, 7 of them are public -- the rest are private for the class to use.
You should avoid static as much as global.
Statics give you the same disadvantages globals give you. Whenever you are using any class methods, you are hardcoding a dependency on that class into the consuming code. The result is less maintainable tightly coupled code. This can easily be avoided by avoiding statics altogether and a disciplined use of Dependency Injection.
You cannot inject and pass around static classes, so for instance when you have to unit-test them, you cannot mock them (or at least only with some effort). It's just plain painful. Static methods are death to testability.
Also, keep in mind that classes should do only one thing. They should have a single responsibility. Go through your class to see if there is stuff in there that's better placed somewhere else to avoid writing a God Class.
It depends on the purpose of this class. If the methods are mostly incoherent in terms of data, this is a perfectly valid solution of grouping functions (now methods). This is a very bad idea if you need to share values between functions, since that would be more than a simple list of functions, grouped under a common name. Namespaces are another option, but if you're using a PHP-version lower than 5.3, this is probably the best solution.
This is like saying, "I have a house with four bedrooms. Is that bad?"
Static methods are neither good nor bad. Having fourteen methods is neither good nor bad. Having fourteen static methods is, by extension, neither good nor bad.
If in your fourteen methods you're going to great lengths to simulate object instances, or to simulate inheritance, then something has gone horribly wrong. PHP will let you create instances, and supports inheritance, so it would be silly to try to simulate them any other way.
But if you're just using your class essentially like a namespace, where the functions and data all work together but there are no individual instances of the class to contend with, there's absolutely nothing wrong with that.
Not bad. However, with all those static props, you might want to consider making this a singleton.
Here is some singleton code I am using in the framework I am building. You can tear it apart and make it the sole public method for your class that returns the one version of itself.
class ClassName {
function getInstance()
{
static $instance;
if (!isset($instance))
{
$instance = new ClassName();
}
return $instance;
}
}
You would use this, then, by doing ClassName::GetInstance()->othermethod();
The class can then have tons of private values and otherwise gain all the nice things you have with an object.
I would say that no, it isn't bad. In fact that was the only way to fake certain behavior before. It was for instance a way to fake namespaces. One could encapsulate functions in static classes instead of having them "out in the free". So allot of php developers are familiar with this and it won't actually confuse most people. What you SHOULD try to do nowadays though is to make use of PHP's "new" namespace feature and if needed combine it with a singleton pattern if you actually need to store data in an object format. You could just as well have a "global" variable contained in your namespace and that could work fine at times to. But take a look at namespaces and see if that fits you in any way and after that see if singleton pattern might match your specific needs.

Why should I use classes rather than just a collection of functions? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What are the benefits of OO programming? Will it help me write better code?
OO PHP Explanation for a braindead n00b
Just started learning/playing with creating classes in PHP and I'm wondering what pain do they solve? It seems like I can get the same job done with just a collection of functions that I include into the file. So my question is: Why should I use classes?
The Three Pillars of Object Oriented Programming. Learn them well:
http://codeidol.com/csharp/learncsharp2/Object-Oriented-Programming/The-Three-Pillars-of-Object-Oriented-Programming/
Encapsulation
The first pillar of object-oriented programming is encapsulation. The idea behind encapsulation is that you want to keep each type or class discreet and self-contained, so that you can change the implementation of one class without affecting any other class.
Specialization
The second pillar of object-oriented programming , specialization , is implemented through inheritance ; specifically by declaring that a new class derives from an existing class. The specialized class inherits the characteristics of the more general class. The specialized class is called a derived class, while the more general class is known as a base class.
Rather than cutting and pasting code from one type to another, the derived type inherits the shared fields and methods. If you change how a shared ability is implemented in the base class, you do not have to update code in every derived type; they inherit the changes.
Polymorphism
Polymorphism allows values of different data types to be handled using a uniform interface. The primary usage of polymorphism is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run time
See also:
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
http://en.wikipedia.org/wiki/Type_polymorphism
It's a way to view your code in a more intuitive, real-world way. (You package the data and all possible operations on that data together.) It also encourages encapsulation, abstraction, data hiding... What you're really looking for is the advantages of OOP.
Basically, classes allow you to put your data with the code - i.e. organization.
Also, classes allow your "followers" to customize your classes without rewriting your code, but rather creating new inherited classes.
Every class-based code might be rewritten with functions, but it would be much harder to understand.
Generally, its so that you can customize the behavior of that set of functions. Typically you have a bunch of functions that work in concert.
People who use these functions may want to only modify one of them for some special case. Or maybe you provide a class that forces the functions to interact in a certain why, but you can't define what they'll actually do.
A trite example: imagine if you had some library to check that some things didn't overlap.
class Comparator:
def Greater(self, left, right): pass
def Less(self, left, right): pass
def EnforceNoOverlap(self, comparator, left, right)
assert comparator.Greater(left, right) != comparator.Lesser(left, right)
It a way to make your code more granular, with proper data hiding, separation of concerns and some other best practices.
IMO using only functions in your code sooner or later leads to spaghetti-code that is hard to maintain and extend. It's harder to fix bugs, its harder to implement new features, because often there are lots of code replication.
Also you can't use polymorphism in your code design, so you can't work with abstractions.
the classes/object is the way of implementation object-oriented application design. it covered detailed in numerous OOAD/OOP books.

Function vs Objects Best Practice

I am wondering whats the best practices regarding functions and objects. For example I want to perform an action called tidy. It will take my data as input and tidy it and return it.
Now I can do this in two ways. One using a simple function and the other using a class.
Function: $data = tidy($data);
Class:
$tidy = new Tidy();
$data = $tidy->clean($tidy);
Now the advantage in making it a class is that I do not have to load the class before. I can simply use the autoload feature of php to do so.
Another example is the database class. Now everyone seems to be using a separate class for db connectivity. But we usually have a single object of that class only. Isn't this kind of contrary to the definition of class and objects in a sense that we are using the class only to intantiate a single object?
I kind of dont understand when to use a function and when to use a class. What is the best practice regarding the same? Any guidelines?
Thank you,
Alec
For something that does one thing, and only one thing, I'd just use a function. Anything more complex, and I'd consider using an object.
I took the time to poke through some piles of (arguably ugly and horrible) PHP code and, really, some things could have been done as objects, but were left as functions. Time conversions and string replacements.
Functions typically do one specific task.
Objects represent something that have tasks associated with it. (methods)
Use a function for tidy. Plain and simple. ;-)
I'd personally make a 'data' object that handles data then have a tidy method under it.
This pattern will allow the number of tasks you do on data to expand while containing it all in a nice little self-contained chunk.
For your case, I'd make it a function, possibly a static function in something like a "util" class (for which the only purpose of the class is to act like a namespace - it'll group all your random useful methods together). As a rule of thumb, only use an object if it needs to store some data that needs to live between multiple function calls. That's why the database methods are made to be part of an object, because they store a database handle which is used between multiple function calls. Yes, there only ever is one database object, but having it as an object groups all the database-related stuff into one place, making it easier to maintain and keep bug-free.

Categories