functions.php vs OOP [duplicate] - php

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.

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.

Question regarding class with static functions and namespace in PHP

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.

When and why should I use class in php?

I want to know when and why should I use class in php, I read at php.net that a class contains variables (we write var before them) and functions for these variables, so why not use regular functions ? I mean what does class do ?
and thank you.
Often suggested advantages to using an Object Oriented Programming (i.e.: OOP aka: class based) approach instead of traditional procedural programming are that OOP aids maintainability and provides a clearer separation of concerns (in the main due to the fact that an object is effectively a set of data and the operations that related to that data), although well constructed procedural code won't necessarily be significantly worse than a OOP approach.
Irrespective, I'd be tempted to take a look at the discussion over on: simple explanation PHP OOP vs Procedural? as I suspect this will answer many of your questions.
That said, it's worth bearing in mind that there's never a "one size fits all" approach, and sometimes a mix of both procedural and OOP is ideal.
Also, if you're a beginner to PHP (or programming in general) sometimes OOP (especially large frameworks like Zend) can initially seem overwhelming, but it's often worth the effort getting to know them. (It'll pay dividends down the line.)
As a final point, I'd personally say that OOP is generally more of a "systems thinking" approach, in that large systems generally break down (reasonably) naturally into objects. From the perspective of someone who's been using OOP for too many years to mention, I'd also say that it's at the very least worthy of some serious investigation. (The Wikipedia entry is as good a place to start as any.)
Using a class allows you to encapsulate and re-use code. Here's an example (PHP 5):
class car {
public $color;
public function __construct($color) {
$this->color = $color;
}
public function show_off() {
return 'This car is ' . $this->color;
}
}
// And now I can re-use the code elegantly:
$car_one = new car('blue');
$car_two = new car('red');
$car_thr = new car('yellow');
echo $car_one->show_off(); // This car is blue
echo $car_two->show_off(); // This car is red
echo $car_thr->show_off(); // This car is yellow
I must say that, like you—when I was still very green—I felt like OOP was a solution in search of a problem. But, after diving in and using it, eventually it clicked.
Objects, in their simplest form, are like containers of logic and data that you can pass around. This can be very advantageous.
And yet, I remember my mindset when I first started learning OOP. The above example would not click. The only way to appreciate it is to use it. Once you do, you'll be very glad you did.
Classes are a convenient way to group data and functionality. You could make a class to contain person information. Then, if you want a list of persons, you can make an array and put in it an instance of the class for each person. You fill the variables of the instances with data for the persons. This looks a lot like a two dimensional array (like an array of array of persondata), but it is more. You can build functions that are contained in the class that operate on the variables in the class. You could hide functions and variables from outside, so when you're building a framework you can distinguish between internal and external functionality.
And then, there is not even spoken about inheritance, which gives you even more possibilities.
All of this can be done in procedural code as well, but OOP (for Object Oriented Programming, which is programming using classes) gives you a whole new view on structuring your code.
Many big books have been written about this subject, so it is impossible to describe the exact details and possibilities in this post. All I can tell you is that you should give it a try, keep trying a while during the initial frustrations you'll encounter. And then, when someone else asks you this question, you'll advise them the same thing. :)

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.

Utilities file in php?

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

Categories