Utilities file in php? - 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.

Related

PHP: Should I be creating objects of this class, or is static acceptable?

I have a couple questions regarding best practices and performance for this project I am working on. Forgive me for the huge question.
I'm currently building a text-based game with PHP and MySql that is about 2,500 lines in the core file so far. Currently, this is a library of completely modular functions. Some used for data access, some for data manipulation, and so on.
My first question is this: One class, ItemManager, contains dozens of methods specifically for adding, updating, and deleting game items in the database. The only thing these methods have in common in they interact with the database. Currently, the constructor asks for a mysqli object and then uses that in all it's functions. However, once I add MongoDB into the project, some of these functions may be interacting with a different database.
Would it be acceptable or preferable to simply make all of these functions static? I see no reason to instantiate objects when there would only ever be one, and there is no need for it to maintain class members. So, should I use static methods or not? Why?
Second question: Can someone help me understand the benefit of using classes in PHP BESIDES modularity (as I can achieve that same effect with files of functions)? Coming from a Java background, I recognize the benefit of OOP in a persistent environment, as objects maintain data and states throughout the life of the application. However, with PHP, the life span of a script is a fraction of a second and all state information is stored within a database. Almost all functions just manipulate the database, so what's the purpose? Isn't it pointless to instantiate objects when I can merely call functions? Could I just do entirely static classes containing categorized data manipulation classes without instantiating an object of a class? What are the reasons I should use classes over files of functions? Isn't the basically the same? Are completely static functions acceptable?
Thank you for your time, I wasn't sure how to cut that question into less text, so I apologize.
Would it be acceptable or preferable to simply make all of these
functions static? I see no reason to instantiate objects when there
would only ever be one
There is no reason to instantiate objects if all you ever want to do is what this class is capable of doing. By using static methods you are coupling all of your client code with the class by hardcoding the class name throughout your code base. If at some later point you decide that you might want a different item manager service to fulfill your requests you will most certainly have a bad day.
Note that "a different item manager" can be simply code for "a mock manager used to unit test the rest of your code". So even in cases where alternatives will never be supported, using statics like that makes your code practically untestable.
Of course, you have already mentioned that there could very well be a different item manager in place: if the current one accepts a mysqli object then obviously there is no abstraction layer between your manager code and the mysqli interface. If you want to use a different object to connect to Mongo, how is the current item manager code going to support both configurations? Won't you need to write a new item manager class? How are you going to integrate it with the rest of the code if the class name is hardcoded everywhere?
Let's also view the situation from the opposite side: what does static gain you?
Obviously it makes the item manager a "singleton" object, which may sound like a good idea because "there is only one of it". This idea cannot be dismissed out of hand in PHP (as in other languages where multithreading is supported and there are hidden cross-thread dependencies), but it still doesn't hold much water. If you want your item manager to be a singleton, then simply don't create a second instance. If you want to force this for some reason, use a static variable to count instantiations and throw if you try more than one. Finally, make the class final so that this limitation cannot be removed. The result: a singleton that is not static.
This is all that static has going for it, and in light of the above it's awfully weak to stand as an argument.
and there is no need for it to maintain class
members. So, should I use static methods or not? Why?
I 'm not sure what this means -- you say the constructor already requires a database driver object, which has every right to be a class member. This is another obvious hint that static is not the way to go here.
Can someone help me understand the benefit of using classes in PHP
BESIDES modularity (as I can achieve that same effect with files of
functions)?
I 'm not going to present obvious arguments for OOP here, but raise a counter-point instead: you can achieve the same runtime effect, but you most certainly cannot achieve the same levels of maintainability and debugability for your application. Why use an inferior solution?
Coming from a Java background, I recognize the benefit of OOP in a
persistent environment, as objects maintain data and states throughout
the life of the application. However, with PHP, the life span of a
script is a fraction of a second and all state information is stored
within a database. Almost all functions just manipulate the database,
so what's the purpose? Isn't it pointless to instantiate objects when
I can merely call functions?
The life span of a process is a fraction of a second. The life span of the code base is measured in months, years and decades. That's how long people will be maintaining it, and that's why we use OOP in the first place.
Global variables can hold state just as well as class members, and people have been maintaining state long before "object-oriented" was a term. The benefit of OO is managing the complexity of the source-code-level model of the code, a venture I would most certainly not agree to describe as pointless.
So, should I use static methods or not? Why?
Static methods usually access static variables, which are global state (they are no different than global variables in this regard), which are bad, for many reasons.
Also, while an object instance can be replaced by an other object having the same interface, just by passing an other object to functions using it, static methods cannot easily be replaced. As a result, you can not mock them, and code using them is not easily unit-testable.
If you can, don't use static methods.
1) Stick with the object, as it is easily replaceable or extendable by additional db drivers (e.g. you can overwrite some functions to transparently redirect to MongoDB for special getters.) If you are sure that you will use only once instance, use a singleton, or even better, a regitry pattern.
2) PHPs lifespan isn´t that short. Using an MVC pattern it handles bootstrap, routing, models, business logic and output. So while a single request might only take seconds, it can involve hundreds of classes and thousands of methods.
To stick to your RPG example: One day you might decide to make it multiplayer. Now you can either instanciate a second player-object, or adapt about 500 functions. The former one is only possible with classes.
A great reason is human limitation: It is unlikely to keep the meaning of thousands of functions in mind, especially when working in teams. By using objects, you can define slim APIs. If the player-object has the public methods add_item(\item $item) and remove_item(\item $item), there won´t be a need to keep all those checking, calculating and db-handling functions in mind. You can even ask a fellow developer "create a \monster item with nothing but an attack() method". That´s it, you are done, and cooperation worked at it´s best.
Conclusion If you are from Java background and understand OOP, don´t think twice about ditching that habit. PHP is NOT a pre-OO-script to be used by scriptkiddies. It´s a full-fledged OO environment - but it´s up to you if you take advantage of this.

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.

Design patterns for making old php code object oriented

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.

Usefulness of loading instances in OO PHP?

I was asked to do a project in PHP and to make sure it was object oriented. I've done OO and I've done PHP, but never both.
The main benefit of OO PHP (outside of inheritance/polymorphism) seems to be code organization. That's fine; I'm doing that. But where I get stuck is if I should actually be creating instances for every "object."
To me (and maybe I'm being naive here), a web app is all about making very short, stateless requests to alter or retrieve records in a database. The objects can't persist between requests. So it feels rather pointless to load data from the database, construct an object from that data, make a small update, save the data from the object back to the database, and then throw the object away. The loading/saving code seems to be a lot of work for nothing. [clarification: a waste of development time, not processing time... not too concerned about overhead]
The alternative is to have a bunch of singletons (or classes with static methods) that just provide a nice, organized abstraction layer to the database layer. I guess writing code in this manner just doesn't feel truly OO. Am I missing something or is that style fine?
Yes, you could summarise the benefits of OO as "code organization"; but this is true for all languages (not just PHP). In reality, it's more than that; it's about how you think about your data structures and algorithms, i.e. about how they map to concepts in the problem domain, how they relate to one another (ownership, parent-child, polymorphism, etc.), and how they expose clean, consistent interfaces to one another (encapsulation). If these concepts would benefit your application, and outweigh the extra development time vs. a quick-and-hacky procedural solution, then go for it.
I don't think persistence has anything to do with it.
I think you should question why you've been asked "to make sure it was OO". This seems like a pretty arbitrary request without further justification. Normally, the approach should be to write your application in the style that best suits the requirements, not arbitrary whims...
Singletons are essentially just global variables with some namespace sugar added in. There are a few main benefits to programming with objects and classes that you just don't get from straight procedural programming. One is inheritance, as you mentioned. Another is the namespacing - you can have a code to compress the lot into a single include file (more meaningful in interpreted languages like PHP than in compiled languages).
Objects are essentially a collection of functions with a shared state (though singletons make that a global state. Beware.) As you pointed out the benefit is mostly that that state is transparently shared by the functions without needing to explicitly pass it every single call. If you have various functions per request operating on shared data and wish them to be specialized forms of a general set of functions, OOP is probably a good fit.
Since you have been tasked to "make sure it is object oriented", I'd take some time to consider common groups of functions, generalizations of same, etc.
In the end the setup/teardown time of the objects isn't too bad - and it might even save some development time in the future if you do a good job.
I think OOP is just a programming style and has nothing to do with developing an application. What you need is a pattern that provides a sufficient abstraction layer (for example: MVC).
My recommendation is: Fat-Free.
It's tiny, simple and quickly take you to the minimal viable version of your product. It has everything that you might need (Caching, ORM, CRUD, Captcha...) and is so flexible that you can use any pattern and with your custom directories hierarchy.
Check out the extensive documentation. The only issue is that it requires PHP 5.3. I think it's reasonable considering the options and flexibility it offers. It really changes the way you work; you should definitively give it a shot.
Like most things in life answer is somewhere in a middle.
Todays application use ORMs (for example doctrine for php) for different kind of optimization, better understanding of database approach (which is important for larger dev teams), easier update of the code, abbstraction layer that is well known to people who join the project, caching mechanisms,....
Classes with static methods are just fine if you are doing some smaller project on your own, but when more people are involved in progress you simply need something more robust and standardized.

Classes. What's the point?

I'm fairly new to OOP in PHP, I've made a couple of basic scripts but nothing impressive. All I've really taken from it is that it would probably be easier just make a collection of functions and include them.
The structure of classes seems to just confuse what was otherwise a simple process. And in collating everything into a class it doesn't really add any functionality.
So I'm clearly missing something. Could someone explain what functionality is added by creating classes
Classes are a notion of object-oriented design (and programming and analysis, respectively), where they are used to encapsulate data and methods.
Other object-oriented programming techniques may include features such as
information hiding,
data abstraction,
encapsulation,
modularity,
polymorphism and
inheritance
From an article .. top-15-best-practices-for-writing-super-readable-code:
Object oriented programming can help you create well structured code. But that does not mean you need to abandon procedural programming completely. Actually creating a mix of both styles can be good.
From http://java.sun.com/docs/books/tutorial/java/concepts/class.html:
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.
Finally, a short youtube video about the differences between the procedural and object-oriented programming paradigm ...
While it may at first look simpler to just use a set of functions and include them, classes have their strong points. Classes can store variables and those variables are there "later."
Here's an edited example from php.net
<?php
$item_name = 'Widget 22';
$item_price = 4.90;
$item_qty = 2;
$item_total = ($item_price * $item_qty);
echo "You ordered $item_qty $item_name # \$$item_price for a total of: \$$item_total.";
?>
v.s:
<?php
class Item {
protected $name, $price, $qty, $total;
function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
function calculate($qty) {
$this->total = number_format(($this->price * $qty), 2);
}
public function __toString() {
return "You ordered ($this->qty) '$this->name'" . ($this->qty == 1 ? "" : "s") .
" at \$$this->price, for a total of: \$$this->total.";
}
}
$widget22 = new Item("Widget 22", 4.90);
$widget22->calculate(2);
echo $widget22;
?>
Another huge benefit is that you can make more of them. Say you want to calculate the price of another item and print it. Instead of having to duplicate all the fancy logic, you can just call new Item and be done.
A big advantage to OOP is code reuse. An example: Say you design a generic "Socket" class, which communicates with a server at a very low level. Then, I may come along and decide that I want to write an FTP class, which allows a user to download files while connected to an FTP server. I can "subclass" your Socket class and extend its functionality to support FTP, without rewriting your code.
Now, say John wants to write an HTTP class, to interact with HTTP servers. He, too, can subclass your Socket class to accomplish this, without rewriting the low level socket code.
Notice how in this example there was no duplication of socket code; both me and John shared it. Code duplication is bad because if there is an error in the duplicated code, the exact same bug may occur somewhere else in your code and you may not realize it.
More detailed information about classes can be found on Wikipedia.
Classes are a way to organize programs. Classes can be used to represent entities in the real world, or artifacts in our programming world, reducing the complexity of programs by allowing us to reason about them in terms of a higher granularity.
It is well-known in psychology that experts organize knowledge into "chunks" to allow them to reason more easily and quickly about their domain. Classes allow us to reason more easily and quickly about our programs.
In addition, classes allow us to group together the knowledge about an entity together with the methods/procedures/functions/operations that are naturally associated with that entity. Again, this provides a natural way to organize the information in our programs.
There are other advantages of classes, such as inheritance, but primarily classes are a cognitive way of organizing program structure to reduce the complexity.
Just a coupl months back I was posting similar questions about classes, I have been using PHP for a few years now and I really didn't see a need to use classes, they just complicated a simple process like you said, well I finally decided to jump in on the Class train and I am still learning but I am comfortable using them now and WOW I have a completely opposite way of thinking about them now, I think they are the best feature in PHP now!
I will admit they can be overkill for a small application but a large social network site like mine is far from small, it has hundreds of files and now that I am converting over to classes it is structured much better now and easiar to build, update, manage my code and other users could come in and understand my whole site a lot better now that it uses classes. Another great feature is you can break up all those functions you might have into seperate class files and use autoload() function to auto load the correct file only when the class is needed, this is great on a big project too. Classes make things more plug in play.
All I can say is it's kind of one of those things you need to dive into to see the REAL benefits of it.
I have thought exactly the same thing.
I have read a few books on OO-PHP, my favorite being PHP In Action.
Although when I read the books I thought "Hey, this is very useful and interesting information.", I have yet to use a significant amount of OO-PHP.
Simple needs like getting info from the server and JSON-ing it back really dont need OOP. Im sure it is "Best Practice", but for many people's needs it isn't practical. A few classes, like database connection, and similar data handling can be real time savers, but PHP is sometimes easier and quicker to be used only partially OO.
It would definitely be easy to code in procedural programming (that's what your simple process is called) if your website is small. But as your website grow, you will definitely need to sort things.
For example, you will need classes to act as templates for entities to the database. You might need classes to represent each page, and in a single file you might create multiple pages. Thus these are all advantages of OOP.
In another example you have like 40 over functions. You would want to group them together. Putting them in a class as static methods would definitely help. It'll clean things up so that in future when you come back to the same code, everything looks familiar to you.
I always thought the same thing until I started using classes--realizing that it is so much simpler and better.
You should create those functions that you're mentioning, but gather them all within a class. The functions can then within a class share the same variables, and therefore making it simpler when having to use the same functions multiple times.
The best example I can come up with now is connecting to a database.
Instead of having individual functions that connect, sends a query, fetching the results and closing the connection you could wrap all these functions within a class. This would allow you to communicate to the database multiple times using the same functions, without having to make loads of variables tailored for the specific use on the page.
If you're just writing procedural-style functions then slapping them together into a class you're not going to get many of the benefits of OOP. I think that the Open Closed Principle and the Dependency Inversion Principle describe some of the biggest benefits of OOP, which you wont get unless you intentionally design them into your code.
OOP isn't perfectly suited to everything, though. I think procedural programming is well suited to web development. It involves converting a (fairly) simple request into a bunch of HTML, which is a highly procedural task. If it's simpler to include a few functions, there's no point trying to shove an OOP shaped block into a procedurally shaped hole. However, I imagine that OOP would be the better option if the website was very complex.
All of the above poster have really good points. I would highly recommend the following books:
The OO Thought Process: http://www.amazon.com/Object-Oriented-Thought-Process-3rd/dp/0672330164/ref=sr_1_5?ie=UTF8&s=books&qid=1262547120&sr=8-5
PHP5 Objects, Patterns & Practice: http://www.amazon.com/PHP-Objects-Patterns-Practice-Second/dp/1590599098/ref=sr_1_3?ie=UTF8&s=books&qid=1262546817&sr=8-3
OO Design Heuristics: http://www.amazon.com/Object-Oriented-Design-Heuristics-Arthur-Riel/dp/020163385X/ref=sr_1_1?ie=UTF8&s=books&qid=1262546869&sr=8-1
To manage complexity.
Edit: Maybe I shopuld elaborate a bit more.
Programs are complex entities and many ways have been proposed historically to tame their complexity.
Procedural programming, functions, structured programming, abstract data types and object-oriented programming are just models to help programmers manage the mental effort that is required to understand a program.
Object programming will not solve everything, and certainly for a small script it is overkill, but it works great for big applications or systems.
My original answer tries to summarize the full content of the humongous Code Complete book: do your best to manage complexity and make your programs understandable for you and your successors. It's great if you think that object programming will help you in this task, but it's even better that you question its convenience and try to find better ways.
In PHP, classes can, at the very least, save you a bunch of include statements. The lazy loading of the __autoload() function is very handy. Also, you can be confident that function names in different includes won't conflict.
To go beyond that, you can start to think of creating an API around a class. Functions which are needed only by other functions within the class can be marked private. And eventually, you should be able to ignore the actual code in your classes, and just think of them as API calls.
If I call Do::stuff($a, $b) I get this response.
And that's all you need to know. You can forget how it works "under the hood" inside the class.
And then, of course, there's classes with non-static functions. These can do various interesting things that normal functions can't.

Categories