As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I've been coding with PHP for a while now, but I've been mainly coding with Functions and raw PHP.
I've started to think that I should be writing my code a whole lot neater and more efficiently. I still can't quite get my head around classes. Should I be writing ALL my code in classes?
For example, one of my scripts is a 'permissions manager' - which allows an admin to edit the permissions of various user groups on the site.
Traditionally, I'd have written this as just a script with functions and whatnot. But would it better to write this as a class? If so, what would this class contain? Would I have a separate permissions class for use around the site, and another for the admin-editing area?
Also the site has an API. Should this all be written as one class?
Also, should I be using public (shared) functions at all?
Thanks!
In my opinion everything depends on how large is your project. I've worked using Magento for a while and it's so big that it must be grouped in classes and packets. It's easier to read code and analyse the structure of project if it's split in classes. Also when you need to modify your project after a month or year then good structure helps to re-learn it.
It is useful to write stuff in Classes when a particular set of functions and variables belonging and/or oriented to the same entity or propose is to be used in different environments. It gives a sense of organization, delegation of tasks and avoids repetition of code.
But in situations where the above is false, it is completely disposable. Theres no point in writing a class to something that will run only in one specific place.
Also, if you only want to have a set of information organized in an object-like style like in $user->name, $user->age etc. you can simply do this:
$user = (object)array(
'name' => 'John',
'age' => 20
);
Yes, in my point of view it would be better to make your code in OOP to be more neat, understandable, readable and also for maintenance it will be more easy,
Please take a look here in this stack :
https://stackoverflow.com/questions/4409824/what-are-the-advantages-of-object-oriented-php
You should approach that question from a different angle. Don't just use OOP because you think you have to.
Ask yourself:
Are there parts of my application that I could reuse in other parts of my application? Then these could be taken out of your script and be put in a function or class.
Is there a scenario where you would like to exchange parts of your code to change the behaviour without having to rewrite major parts of your application? Then classes and interfaces are for you.
Another good argument for using OOP principles is the increased testability of your code. Using interfaces allows you to exchange the actual object for a mock or stub at test time.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have a comics website, http://hittingtreeswithsticks.com, and I guess I'm unclear as to which style, procedural or OO, that it's written in.
Basically, there are several "templates", homepage.php, viewall.php, viewFullSize.php, which call upon various scripts... namely, the templates all include imageDisplay.php, which has several scripts which determine how to query based on which category, tag, or subsite is selected.
I've read a lot about the benefits of OO programming- when it's used and when it's not... but am still having trouble answering this question.
The way I understand the difference between OOP and procedural from an example standpoint is:
OOP: If you have a website where a user can create an object, such as a forum where a user can submit a post... then you'd want to go with OOP because you'd want to allow users to create several instances of the Article class.
Procedural: I went with what I think is procedural because my comics website simply displays comics out to users. A user can submit a comment using DISQUS, or like/dislike. I don't see where I'd be able to fit the OOP paradigm into a simple image display site.
So, the question is:
To use OOP, do you necessarily need to have several objects that would be instantiated? Or are there other benefits I'm missing?
Thanks
Do both.
Just call the procedures "methods", or your methods "procedures".
Objects don't need to correspond to real world objects, it's as much about modularization and moving code into isolated (!) chunks as about "objects".
All in all, a website is not the best to understand OOP. Too little inheritance happening.
Instead, write a simulation. For example, a road with maybe a crossroad and a few drivers driving around.
Start with a stupid driver, then try to allow for subclassing it with different smarter drivers. Or aggressive drivers. And see if they can cause more traffic jams.
Try to start with a problem where you have natural objects that share a lot of traits, and only differ in a few.
Always code OOP. The only reason people ever code procedural PHP is because they're using pre PHP 5.
To answer your question, no. You can have a single object. OOP is just for code organization and the implementation of DRY principals.
OO is normally a better aproach, as long as you document correctly and are aware of class dependencies/herance/hierarquy.
Besides adding a bit of security to your code, an correctly implemented OOP is trully powerfull for adding and upgrading new features, organize code, reuse logic.
As everything is within it's object definition, you always know where and what to look for.
Yes, is kinda tricky at times but it pays.
Non OOP is good practice only in basic methods, small coding.
Something like the "Hello world" :p
Or a non server content dependedence of content or better known as static websites.
For OO you don't require an object to have definition like parametters or whatever.
In your case, you could have an object for db handling, another for top menu bar, another that handle comic book related stuff like sorting, listing...
Basicly wraping everything in it's corresponding place, reusing code more efficiently..
Hope this helped
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
i wanted to know the difference between having a collection of functions i could create in a PHP file compared to a PHP class file?
for practical purposes, the CLASS is different because it can be instantiated. When it is instantiated it will have its own unique properties and values.
In this way you can have the same class instantiated multiple times each with their unique properties.
a common example of this would be a character in a game; i.e. you have a class called enemy. you produce 5 enemies by instantiating the class that many times. Each will have their own properties, life, speed, etc... you can access each of the instantiations individually and run methods within that adjust their properties.
A class is a collection of data and functions that can be instantiated (a different set of data for each instance).
Classes are a focal point of OOP, and they exist to organize code with a focus on objects. OOP better facilitates modularity than imperative programming. For your research, it would be better to look at this answer to a different question and the link contained therein.
Functions that are defined within a class construct are referred to as methods, which typically require an instance of that class to work (with the exception of static methods). Such as instance would keep "shared" data between the methods to work with, encapsulating the behaviour of an object.
A collection of functions can do this as well, for example fopen() opens a stream that can be passed to fread(), fwrite(), etc. as their first argument; a similar approach can be made with a stream class, for example:
$f = new MyFile('filename');
$f->read(10);
$f->write('hello');
As opposed to:
$f = fopen('filename');
fread($f, 10);
fwrite($f, 'hello');
A collection of functions is just a random collection of functions. A class encapsulates a specific area of behaviour.
For example, when you are adding a function to a class, you should be thinking "is this the correct and only place for this?"
It is possible to write a class in PHP that fits both of these definitions - but you should aim for the latter.
I think you could imagine the difference between functions and classes in PHP as the difference between the languages C and C++. C was made first and then C++ followed as its Object Oriented version. So is PHP, it was made first based on C, as a simplified C for Web (Personal Home Page) and later added OOP functionality. But the beauty of PHP is in its simplicity, you can make a whole new page in a couple minutes without having any solid programming experience. Using classes in PHP kind of break this purpose as it can overkill if you just develop something relatively simple.
Classes are great for libraries. I suggest you using them. And it's a more advance coding style: creating classes means creating your own libraries which you can use for different projects. Just make sure you don't overuse them. Not for everything in PHP really needs a class, just for those forever-repeating functionalities. Classes add the flexibility and scalability to your projects.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
This is just an opinion question but I don't want to elicit debate. I just want professional feedback on whether it's good practice or bad practice to have your classes do all the work to where you just need to instantiate the object. if everything goes well, then you do the next step whatever it is in your application, within the class. If something goes wrong, you create a function to emit the errors within the class also.
I do all of this with the magic __construct method, and all my properties are private (or protected if i need to extend something)... most of my methods are private/protected also, except for getters and setters which i don't use much anyway, since everything happens inside the class.
For example, I have a login class, and you just feed it the username and password parameters when you instantiate it, and everything happens with the __construct I don't need to do anything with my script using that class. Also... same thing with my registration class.. you just feed it the parameters again and the class does everything. I don't need to be manipulating my classes at all with scripts.
Good practice or bad practice? I want to be a professional and I want to start coding like one, but maybe I'm doing it OK?
I voted to close this since it will probably spark a relatively useless debate.
Anyway, there are two big theories on constructors: single stage and multiple stage. You're doing single stage. Many people argue for single stage. However, I think it's bad practice. Why?
Because it makes it more difficult to test. When you write tests you want to test individual functionality of an object .. but if your constructor does everything that becomes impossible.
It also makes it harder to reuse the object for a different purpose later. Your object may do everything you need it to do except for one extra method call in the constructor -- so now you have to rewrite it a bit and change how it's called in at least a couple places.
The real answer is do what you're most comfortable with in the confines of your project.
The method __construct should only instantiate (validate/prepare values for instantiation) object and nothing else. That's all. It's not logical that your class do all the work in the constructor.
EDIT:
Good practice:
Application app = new Application(context); // create application
app.run(); // run it
Bad practice:
new Application(context) // create & run application
[just my 2 cent]
To be honest, you might as well just use a function for what you describe.
It seems to me you are using your Class as a collection of functions/functionality.
This is OK, and it makes your code more structured, but you don't really use the power of OOP.
The real power of OOP isn't only the fact that you can bundle functions conceptually (which can also be done with appropriate include files that hold conceptual related functions), but the real power of OOP lies more in the fact that you can subclass useful existing Classes.
In my opinion, don't feel forced to go fully OOP if you feel uncomfortable with it. All tasks done with OOP can also be done with procedural approach.
And often, for more mundane tasks, procedural approach is faster to program, and is just as clear as object oriented.
This question is along the lines of "is it better to use an integer or a floating point". Well, it depends on the situation.
What WORKS and what is "standard" are not the same. If your method works, and for you is easy to debug and maintain, then it's a great solution to use.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm teaching a few friends some basic object-oriented concepts in PHP and i wanted to give them some real-world examples, but simple, so they can grasp the syntax and the basics of OO. I already gave them the following exercise: create a small class that abstracts HTML form creation. You can create objects for each form field, each type of field has a class. I also have a form class which receives form field objects.
Do you guys have any other ideas of examples or exercises? Thanks!
My blog post about Objects in PHP might be useful:
http://agiletoolkit.org/blog/how-to-use-object-oriented-programming-in-php/
It gives example how to macerate "geometry" classes, triangle, vector, square etc.
When I was learning OOP, I was reading a book with similar examples in C++, but I forgot the name.
A simple exercise I've always enjoyed for getting into an object-oriented way of thinking is to take some simple real-world concept and model it into objects. These concepts can be anything:
A coffee maker
A chicken
A bicycle
etc.
It's very language-agnostic, platform-agnostic, etc. The idea is to abstract out all of the implementation details (things like PHP and HTML) and focus on object-oriented thinking. How does a model for such an object look? What are its attributes? What are its constraints? How does it behave? How does it interact with other objects?
You can effectively design your abstract types by their external observable characteristics and behaviors, their interactions, etc. and then implement those abstractions in PHP or any other language of choice. But the point is to separate out the object-oriented thinking from the specific implementation.
Some things that are usable/practical:
Almost everybody seems to start with a database abstraction library. Very simple to do
Abstraction for different caching libraries (memcache, apc, file cache)
Perhaps a simple router
Try a table generation class, where they receive an array and, depending on it's contents, a table is displayed.
It depends on how much they know already, if they have experience of programming in C++/C and are starting OO, then examples from Databases, forms, vector etc would work, if they have relatively little experience, then you have to start with abstract or real life examples, examples quoted in another reply
A coffee maker
A chicken
A bicycle
etc.
will work great (despite you have mentioned you do not like such examples) in understanding the concept of Object Oriented and the theory behind it. They have to see how everything works together to form a machine, how each component (class) works and interacts (public methods and interfaces) while hiding its own functionality, and providing a set of services to other components (classes).
A very popular examples teachers give is of a radio, where the user doesn't know what is inside the radio and how it works, the user only knows what it does, and the radio makes its features available to the user for use through the buttons on the panel.
These basic examples work well for beginners, and then immediately there should be a programming assignment related to it. Once they understand the basics, programming and application examples instead of abstract examples should be used in my opinion.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I would like to implement MVC from scratch in PHP because I want full control of my own code
and no extra bagage from existing frameworks. Anyone who has any advice?
Yes, I've seen Lerdorfs article and it seems that it ain't so much code after all. Actually I would more like to have a controller-view solution for structuring my application. I'll stick to my own homemade PDO data-access classes.
Your question somewhat smells like Not-Invented-Here-Syndrome. In this case, my advice would be to live with the extra baggage of existing frameworks when you can be sure they are thoroughly tested and supported. Don't reinvent the wheel.
On the other hand, the above argumentation would prevent new frameworks to be written. And writing one from scratch is a good coding exercise to learn and understand the MVC pattern.
So if you are really determined to do it, my suggestion is to learn what each part of MVC is, does and how they interact. You will inevitably come across the FrontController pattern as well, so you will want to learn about this one too.
Note that you are not the only person wanting to do this:
http://www.google.de/search?q=front+controller+php
http://www.google.de/search?q=build+your+own+mvc+php
And there is also this interesting article by Rasmus Lerdorf
http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html
A simple exemple implementation of MVC (just to understand the principle)
MODEL: lib/Thing.class.php
class Thing
{
//class code ( CRUD, the application logic ...)
}
VIEW: theme/page_thing.php
<?php require("header.php");?>
//HTML CODE with some echo to show variables and loops to read arrays
<?php require("footer.php");?>
CONTROLLER: application/thing.php
require_once("lib/Thing.class.php");
/*
Some controls between the Model and the View ( if/else ...)
*/
include("theme/page_thing.php");
I, too, wrote an homegrown MVC framework in PHP. Its pretty simple, especially when you remove any "ActiveRecord" functionality from your frame work. Some things that I considered:
How are you going to map URLs to controllers?
Instead of doing things by convention (/foo maps to FooController), I did everything via configuration. That is, I have a master routes.php file wherein I list every possible URL that my application will accept. So its filled with things like:
Router::add( '/foo/:Param1/:Param2',
array( 'Controller' => 'MyController',
'Action' => 'my_method',
'Method' => 'GET',
'Parameters' => array( 'Param1' => '\d+',
'Param2' => '\S+' ) );
In this case we match urls like /foo/123/abc. When the URL is matched, it is dispatched as MyController::my_method( array( 'Param1' => '123', 'Param2' => 'abc' ) );.
How are you going to generate views?
There are lots of templating systems out there. But really, PHP is already a perfect templating system. In my framework, I just created a function template() in the top-level Controller class. And it all boils down to performing an include $Template. Again, in my framework, there is no convention. Each controller is responsible for instantiating the appropriate template, and for understanding if the request is expecting HTML, XML, or JSON as a response.
Can you use an existing framework?
A lot of my code was inspired by Cake, the well-known PHP MVC framework. I'd definitely take a peek at it before you proceed to far. If you're going to roll your own, at least start by understanding how all of the popular ones work. In the end, the peculiar requirements of my application made me go down the road of build my own, but there was a lot to be learned from all the frameworks already out there. Take a long look around, and you may find something that works for you. At the very least, you may figure out exactly what you need out of your framework.
I personally use my own framework consisting of :
1.Mysql Interface
2.Template System (yes home brewed not smarty)
3.Config Class (mysql details,debug, and anything else that the script might need)
4.Simple Form Creating class.
5.a Request Class (all useful details from $_SERVER in a more readable format ex: $this->Request->ip, $this->Request->url,$this->Request->time)
6. Anti-hacking (Ip blacklist, keywords from public sec. scanners etc.)
And I just call it framework :)
if you're just going to "recyle" the wheel, you can take a look at the source code of "popular" frameworks. if you want to "reinvent" the wheel, i suggest you look elsewhere. examine domain-specific languages (DSL).