Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm developing a web system using regular PHP. This was my first experience with PHP so the code is not legible nor clean. It mixes some HTML code with PHP.
I'd say I have already done half of the code.
What are the real advantages of the Object-oriented PHP?
The website is about books and book authors, using MySQL and Apache. So it's not a very complicated website.
The real advantage of object-orientation: your code is better organized, easier to maintain, more modular (and thus easier to reuse), and potentially less brittle (because of encapsulation of state and implementation, and hopefully better security). (The cynic in me also says that if you learn object-oriented PHP, you take the first important step to leaving the PHP ghetto. Heh. Worked for me!)
There's already a lot of questions from PHPers moving into OO on Stack Overflow:
PHP Object Oriented or Not?
Is my PHP code object oriented?
Learning PHP Class
Not to mention that there are zillions of PHP object-oriented tutorials out there. My take: basically, yes, if you are writing PHP, you should probably be writing object-oriented PHP for anything beyond the most trivial of applications. There are lots of Rails-like frameworks for PHP that will make your life easier, and may help you become a better programmer.
Object oriented PHP does not differ with the procedural style in the amount of HTML code you mingle with PHP code. So if your only concern is the mix you should look for other ways to get your code cleaned. For example you can create html template files with placeholders for your dynamic content and use file_get_contents and str_replace to inject the dynamic content at run time.
In my mind, we PHPers can thoroughly throw away the concept of Object (class instance), we only need Array and Mode Class:
All arrays in initial mode support any array function as its method:
<?php
$array1->array_flip(this);
?>
Use "->mode()" to validate the minimal data set, and then switch mode class:
<?php
$array1->mode('class1', $success);
?>
Any mode class has no "->construct()" in it, but has "->validate()" to validate the minimal data set.
The array in a mode still could use array function as its method, but after using any of them the array will be switched back into basic array mode,
and we need to use "->mode('class1', $success);" to switch mode back.
The radical thought here is data-centric programming; we need to separate the data (array) and the activity (class method).
We could modify the PHP engine, to get rid of parts of OO (object oriented), and support Mode Class. We could call it MyPHP.
For example:
$array_man1 could be set into two modes: cls_normal_man and cls_crazy_man:
<?php
$array_man1->mode('cls_normal_man')->normal_method1()->mode('cls_crazy_man')->crazy_method1();
?>
if you really want to use oo programming go to Ruby.
OO PHP for me is a fake. And if you already have half of code done in structural php dont change your mind.
just remember to make code clean with lots of comments so you can easily change sth in the future
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I've been trying to find out if I can apply the MVC architecture to procedural and how I can go about implementing this into my code. From my understanding MVC basically represents the separation of the business logic, presentational layer and other logic although it always seems to be aimed at OO-PHP in particular.
Can you recommend the best way to approach MVC within a procedural context??
Thanks.
MVC is OO pattern and you want to approach it with a procedural context.
This is plain wrong. MVC has nothing to do with object oriented coding.
MVC is a software architecture pattern which aims at separating the representation of information from the user's interaction with it.
How you achieve that is up to you. You can achieve that using whatever coding form you want, object oriented, procedural, functional, and what not.
With regard to the question at hand: The easiest way to achieve the MVC pattern when you're coding procedural PHP is to use a lot of small functions where each particular function has its own unique task. Don't let a function have many tasks. That way it is more easy to separate things. Also don't keep a lot of functions in the same file. Rather gather related functions together in smaller groups each group in its own file (what actually is done in OO with classes).
Someone does it here with a simple example, MVC without OO: http://www.fluffycat.com/PHP-Design-Patterns/Non-OO-MVC/
Yep, that about sums up MVC... but it doesn't have to be object oriented... you just need to follow a few golden rules:
The controller receives and processes input, generates any data and puts it in the model.
The view takes data from the model and renders it.
The controller should not format data for view - it should have no knowledge of how/why/what the view wants (eg doesn't insert HTML in a text string since the output could be JSON)
The view should not look-up any data for itself - if it's not in the model then the controller failed in it's job (throw/report an error).
Beyond that you can do things however you want. You'd basically need a set of procedures to act as controllers - parsing $_REQUEST vars (more likely as GET/POST/COOKIE) performing any data lookup building + filling the model, and then another set of procedures that at as views - taking what's in the model and rendering it for the user. The model can be as simple as an associative array.
Absolutely. Use any combination of the following:
Use include files.
Use functions.
Separate your source files.
Divide sections of your code within source files.
Use code blocks (curly braces).
Separate PHP and/or HTML and/or JS files.
Anything that organizes your code more along the lines of Models, Views, and Controllers. It may not be "pure" or "correct" MVC in some people's minds...but if it organizes your procedural code more meaningfully or teaches you more about MVC, then it's a good thing.
This is kinda weird.
MVC is OO pattern and you want to approach it with a procedural context.
The first thing that comes to my mind is to have some kind of templating engine in order to split the PHP from the HTML code. This will be one big step towards procedural MVC :)
The next thing is to name functions of the same group (that means, functions that contains logic for related objects) with prefixes (like you group methods under a class name).
For example - look PHP procedural functions for working with mysql :
mysql_connect()
mysql_real_escape_string();
mysql_select_db();
mysql_query();
etc.
And group those functions in separate files. This will help to decouple a bit of the logic too.
If anything else come to my mind, i'll edit my post :)
If you are implementing a new design pattern you most likely are refactoring or writing something from scratch. I highly recommend moving to OOP if you plan to use MVC. It could be implemented procedurally but will be very hackish and not a good solution.
There are several free MVC php solutions that you can pick up easily. Here are a few:
Zend Framework
Kohana
Code Ignighter
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 12 years ago.
Improve this question
The vast amount of frameworks available for PHP now use MVC. Even ASP.net has its own MVC module.
I can see the attraction of MVC, I really can and I use it frequently. The only downside that I can see is that you have to fire up the whole system to execute a page request. Depending on your task this can be a little wasteful.
So the question. In a professional environment is this the only way to use PHP nowadays or are their other design methods which have alternative benefits?
I don't like anyone telling me how to write a code. If I want to use MVC I will, if I find a better way that solves specific task, I will use it. I don't like when people turn MVC into a religion. I also think many php coders misunderstand the MVC concept and think they are using MVC pattern when in fact most of the times that are not using a 100% pure MVC. The truth is that it's not easy nor very efficient to write a website that is 100% MVC and is written in php.
Most people having most difficulties in the "V" part of the MVC. The "M" is easy. It's your data. If you storing your data in the database and have a database access class, that's your "M" part, you good with "M"
Now the controller: when user clicks on any link of your page, your php code must get the data from the "M" (database), prepare it, apply some logic like adding personalization to logged in user, adding "please login" link if user not logged it, etc. This is your "C" part.
The problem that most people are having with is separating the "V" View from "C" (controller) This is not easy nor is it the most efficient way to code in php. In many cases the controller part must already generate some html, so you blur the line between controller and view.
If you want to stay pure MVC then you must make sure that your controller returns a pure data, then the View class takes some template, plugs in your data and returns the HTML. This is where the problem lies in php. There is no easy and efficient way to do templating where a template just takes a pure data as input and returns the html. If there was an easy way, then there would not be reason for people to keep coming up with yet another new template library. The reason the there are so many templating libraries for php is because there are always programmers that are not happy with ANY of the existing ones and keep trying to invent their own, better one.
The only pure templating library in my opinion is the XSLT, which is fully supported by php, it's comes with php, it works, it's powerful, great templating engine, better yet, it's a standard, platform independant language. Once you learn XSLT you can use it in any other programming language like Java. But it does have one tiny problem, however. It requires the input to be an XML. Sure, you can create a great, 100% valid XML in php also using DOM library which is also part of php. The problem is that it will be slow. You will be doing double the work: first creating XML from your array of data, then trasforming that XML into HTML with your XSL template. This is why the approach of XSLT as templating engine never took off in php.
Now you left with the other options to parse templates, usually its regex based approach. You see how it always gets complicated when we get to the "V" part of the MVC?
The "M" is easy, the "C" is some type of pure php code, be it OOP or procedural code, does not matter. It's the "View" that is the tricky one.
So my advice is - don't worry too much about sticking to pure MVC. It's OK for a controller to spit out chunks of html here and there.
Well there are a lot of other approaches.
MVC is just popular because it suits most situations (or better said can be used in most situations) and has established itself as a de-facto standard.
What can be said is that every programming/design pattern - or more specific architectural - depends on some classification.
Those are often (of course they can be devided further):
User Interface (pretty images, forms etc)
Application (your application logic and stuff that needs to be secured from the client - ak lot of that can often be done in the user inteface, eg. by javascript)
Database - self explaining
Infrastructure (very basic stuff like hard disk, server systems, network etc.)
Of course there is always the naive, procedural straight-forward approach but also a lot fo other patterns that can link and structure the access and controlling to these basic layers.
Mvc is one of them. But here are some example of others:
http://en.wikipedia.org/wiki/Model_View_ViewModel
http://en.wikipedia.org/wiki/Model_View_Presenter
Is MVC-ARS preferable to classic MVC to prevent overloading?
And here a lot more:
http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
PHP as a Blunt Instrument
I hear PHP getting bashed around a lot lately. In quite a few projects, I have seen insane php code bases - so bad you really wonder if the person was on hallucinogenic drugs when they wrote the code. Sometimes, I wonder what the code would have been like if the initial developers had a bit more guidance as to what not to do.
However, I have also seen some very well organized PHP projects that were done in 100% OOP and were a pleasure to maintain, but they were not written by "php programmers."
I give all of our junior devs a link to Java Anti-Patterns. One of the nice things about that page is the Java-specific examples because there are many features of Java that lend themselves to common mistakes. I was hoping to find a similar list for php, but a google search did not reveal anything meaningful.
There are a few questions already out there for what a developer should know when programming PHP, but I wanted to focus on the negative.
What are the common things you have seen in PHP that should be avoided and what is a common solution to doing the same thing in a better way?
Some of the obvious examples to me that I think will be mentioned but aren't PHP specific:
Don't concatenate SQL. Use prepare statements or proper escaping.
Don't blindly embed PHP into HTML - use templating/MVC.
Don't blindly post raw unfiltered user input - scrub it for XSS attacks.
Don't manually try to parse all of your POSTs and GETs - use a web framework.
Here would be some examples that I would consider PHP specific:
Don't have too many layers of file include/require linking and try to avoid conditional linking. Rather, have a sane naming convention and be consistent with your organization.
Don't use PHPs raw database API unless you can help it, instead use a database framework like ADODB instead.
Don't overuse PHP's dynamic typing by setting the variable to a string in one place and a boolean somewhere else, then expecting the boolean tests to make sense.
So, what are your favorite PHP don'ts and how do you do it right?
I disagree with this one:
Don't blindly embed PHP into HTML - use templating/MVC.
PHP is a templating language. While I agree with the concept of implementing MVC, I don't see why there should be a requirement to implement a yet another DSL around producing web output.
Adding closing "?>" tags to the end of php files can lead to accidentally pushing white-spaces to the output buffer. The PHP interpreter will automatically add closing tags to files, and doing it manually is somewhat of an anti-pattern.
Never EVER use a $_GET or $_POST without checking it and cleaning it up.
Read about how to set up the php.ini right.
Never put variables into raw SQL.
If you use frameworks, use the ones with less dependencies.
Stop over-generalization.
Distribute your code on the php files. In most cases there is no real need to put everything into one index.php.
Reduce complexity before writing code.
Respect the fact that it is a web application. (Try to be RESTful.) It's not a desktop application. So stop putting everything into $_SESSION.
At least one comment line for every 10 lines of code. You WILL read that after a year. I promise!
Code like a girl - make it nice to read.
My current pet peeve is inconsistent-return-type for query-functions. This is when you call a function to execute a query, and it returns
NULL or FALSE or something similar when no match is found
The matching object/value when a single match is found
array of matching objects/values when more than one match was found
which forces you to check the return types and deal with each case specifically. It would be much better to simply always return an array with 0, 1 or n elements.
One of my favourite DON'Ts would have to be:
$query = 'select * from users where username = ' . $_POST['username'];
Can it get much scarier than that?
If I had to include a favourite don't it has to be the one posted by karim79:
$query = 'select * from users where username = ' . $_POST['username'];
Many developers in PHP keep stuck in structured age. PHP supports classes and objects since a while ago, I just don't get why people keep hard coding PHP into html, without templates or nothing at all.
I believe that developers from other languages, like .NET or Java have earned the right to criticize the language if so many developers keep programming like that. PHP is a very great language, very flexible, still a little junior but is growing, but many just don't get it, all they want is to solve by making the old classic copy & paste.
use SPL
use PDO instead of using mysql_query or pg_query or others
always use the filter extension on user input
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
What's the best/easiest to integrate templating system for PHP, and what are the benefits of using one?
I currently don't use one at all, and am thinking that it might help to seperate content from presentation a little more.
PHP is a pretty good templating language by itself. Most leading PHP frameworks don't use a seperate templating langauge for just this reason.
Just make sure you use (something resemebling) MVC, and don't do any data access or business logic inside your view files.
I've also used Smarty extensively, but find it has little advantage compared to straight PHP, except for forcing you to keep your view dumb. It might also looks a little better to designers, but the down side is flexibility to you, the template implementor. Things like looping over triply-nested arrays become harder than with straight PHP.
Smarty
I've found it to be fast, easy to use, and easy to install (even in a shared-hosting environment). It also doesn't require that you use validating XHTML which is handy sometimes (although I think the template engines that do require valid XHTML are probably faster.)
It's really nice to have your content in one place and code somewhere else.
Plus you're not limited to just HTML. I've used Smarty to generate XML and even SQL.
To follow up on what Alex said, I suggest taking a look at Rasmus Lerdorf's article The no-framework PHP MVC framework.
Rasmus Lerdorf is the guy who created PHP.
I bet on PHPTAL.
It checks file syntax and ensures output is well-formed XML with proper escaping. This ensures that pages are safe against XSS attacks without programmer having to worry about it every single time.
Smarty and raw PHP don't handle escaping automatically, which means that every echo $foo or ${foo} (without |escape} or htmlspecialchars()) might be HTML injection vulnerability or at least break well-formedness.
PHPTAL has nice syntax that fits how HTML/XML work, e.g. you don't have to repeat yourself when you want to conditionally wrap something in a tag:
<strong tal:omit-tag="condition">
xxx
</strong>
rather than:
{if condition}<strong>{/if}
xxx
{if condition-again!}</strong>{/if}
And the syntax is XML without being overly verbose (mostly only attributes are added). There's no ugly mix of HTML and custom tag-like constructs.
In addition to Mark's experience, I've found Smarty well-suited for extension. I've built a (corporate) MVC framework with built-in views based on Smarty which was both easy and is flexible. The host of available template helper functions can also be extended very easily.
Perhaps the most compelling reason to use a template engine is default output escaping which can reduce or eliminate xss vulnerabilites.
It depends on your focus: different template engines can be better for different things. Smarty is relatively heavy compared to some, and defines a syntax that is simpler but more restricted than PHP's. There are benefits to using a syntax that is less like a programming language, for example if you're going to be asking a graphic designer to build your templates.
A template engine such as Savant3, or that used in the Zend_View components of the Zend Framework is lighter-weight and uses PHP as it's syntax. This gives you more power and flexibility in your templates, but requires you to be disciplined about keeping business logic out of the templates. Also, PHP syntax may be too complex for your designer, if he is going to be building the templates.
I personally like the idea of just using separate PHP/HTML files. It allows me to use other HTML editors if I want (such as DreamWeaver) and can also allow people who don't know PHP, but do know HTML to edit the templates without having to learn another language.
I have used Smarty for years, but got frustrated because the special smarty syntax got in the way, where some simple php would be way easier. PHP itselves is in its very core a template language! I learned that the php api is apt enough for all presentation logic.
Savant3 and its descendant Zend_View are therefore superior solutions. Like in Smarty, you can easily write plugins for repetitive tasks.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a start of a webapp that I wrote without using the Object Oriented features of PHP.
I don't really know if it is worth it to go back and rewrite the parts I have finished. Is object oriented PHP worth rewriting all or part of a decent working app?
Given that you have an incomplete app I would say that reworking it into an Object based app will probably be helpful.
One thing to consider is the expected size of the end application. Below a certain complexity Object based may be overkill except for the learning experience.
I started out avoiding Objects like the plague because my initial introduction to them in university classes was terrible. I somewhat recently had to work on a project which was implemented in php objects. making the required changes was much easier than other projects. I have since then worked in the object model frequently and find it very handy for quick creation and easier upkeep.
Just to disagree with the consensus... I would say no in most cases. Not as an academic exercise on commercial code anyway. If it's working don't re-write it. If you have to go in to change / add bits, then refactor towards OO practices (there are lots of posts on SO about refactoring when you are changing code anyway, and not just for the sake of it).
In practise if you haven't done a lot of OOP, then you'll want to start small and get a feel for it.
Once you get a handle on the basics, a good beginners guide to Design Patterns (I like the Head First book) is very useful. Most PHP books would teach you OOP fairly poorly. They teach you about inheritance, but usually don't teach you about loose coupling and favouring composition over inheritance. A design patterns book will give you a better insight into this.
PHP still has a reputation for not "doing" OO right. I don't think this is fair, but is a reflection of the fact that it's so easy for people to get started without really grokking OOP. I would go out on a limb and say the majority (ever so slightly - call it 51%) of PHP programmers aren't comfortable with OOP. I think it's possible to do good OO in PHP, and if you're already comfortable with the language it's a great way to grow your skills.
EDIT:
Just to add a couple of disclaimers...
My comment about most PHP programmers not being comfortable with OOP wouldn't apply to the current SO audience!
Not suggesting you aren't comfortable with OOP, this applies if you're not
Typical answer: "It depends."
I tend to write the display page as a start-to-finish, < html > to < /html > scripted page. But the things that happen on that page were objects. Kinda like a poor man's ASP. While you can have OOP-base output, I alwasy thought it too cumbersome for a task as tedious as dumping data to a browser.
So, business rules and data access were OOP. Presentation was script.
If you have business rules that are not OOP, I would seriously consider writing those as objects on two conditions: (1) is "Do you have time/effort/money to do so?" and (2) is "Do you have a good PHP IDE that will make your life easier?" If it works, and changing it means writing in Notepad++, then I would call it done. :-)
I wouldn't say it is critical, but if you are going to go much further with the app, I would recommend doing it now while it is not as much of a monumental task. I would say the maintainability of a well written OOP program could far outweigh the up front costs. Especially when you consider that you will be able to refactor much of the code as you go along.
Learning object oriented techinques will be really useful, especially for programming in other languages in the future.
Since you have only just started the application, you could rewrite and improve the parts you have written. It depends on your deadline.
There are two possibilities: either your app is a one-off that just has to work right now and will never be touched, adapted, expanded or modified, or else your app is the beginning of something that you will keep working with and using over a long time.
If the former, don't break perfectly usable code. You have better things to do with your time.
If the latter, you have to bear in mind an important fact about PHP, which is this: poorly written PHP is a nightmare to maintain. Not as bad as poorly written Perl -- because what is? -- but bad enough that sooner or later you will feel a strong urge to steal a time machine, travel back to the moment you wrote the code you now find yourself maintaining, and stab yourself in the eye socket with an icepick.
So if you're going to be maintaining this code over time, take the time to do it right. That means: some kind of templating system, no PHP tags embedded inside HTML, separate files for separate functionality, and classes classes classes!
Your eye sockets will thank you.
I would say try and go OO just because what you have can be reused much easier than procedural if done right
I will also say that OO is much more organized then procedural. When your at a small scale it's easy to get away with sloppy code OO or not. But when you get to larger projects your procedural must be much more organized and thought out. Where as on some larger projects OO tends to force you to be more organized making things a little easier.
No, i think if the app is working like it should there's no need to rewrite it.
PHP isn't really OOP at all. They try hard but sometimes i think even the PHP-Developers dont really understand the sense of OOP.
If you wish to learn OOP (which is surely a good idea) try a real OOP-language like Smalltalk to learn the basic concepts. Java is also nice 2 learn the basic, although it isnt fully OOP as well
I'd like to reiterate the other answers here. It depends upon size of application and how much you'd like to learn about OOP. I'd be careful of learning OOP by using PHP though.
As for how much PHP is object oriented... PHP4 had some OOP elements slapped onto it, PHP5 is better but it's not baked into the language. PHP works both ways, and personally I like that you can choose.
In my mind, we phper can thorouly throw away the concept of Object(class instance), we only need Array and Mode Class:
All arrays in initial mode support any array function as it's method:
<?php
$array1->array_flip(this);
?>
Use ->mode() to validate the minimal data set, and then switch mode class:
<?php
$array1->mode('class1', $success);
?>
Any mode class has no ->construct() in it, but has ->validate() to validate the minimal data set.
The array in a mode still could use array function as its method, but after using any of them the array will be switched back into basic array mode,
and we need to use ->mode('class1', $success); to switch mode back.
The radical thought is data-centric programming, we need separate the data(array) and the activity(class method).
We could modify PHP engine, to get rid of parts of OO(object oriented), and support Mode Class, we could call it MyPHP.
For example:
$array_man1 could be set into two modes:cls_normal_man and cls_crazy_man:
<?php
$array_man1->mode('cls_normal_man')->normal_method1()->mode('cls_crazy_man')->crazy_method1();
?>