Avoiding Bad PHP Coding - php

There is a lot of books and tutorials about php that are completely different from each other.
How can I choose the right way? Is the only way is test with xdebug or phpUnit or benchmark?

Have a look at the slides and the tools given at
Quality Assurance in PHP Projects
Disclaimer: I am not affiliated with Sebastian Bergmann or thePHP.cc - they just happen to be major influence on the code quality topic in the PHP world, which is why I suggest this link.

General Best Practices
As code quality/readability/maintainability cannot be "benchmarked", I suggest reading books about proper code structuring and best practices.
Maybe Code Complete book from Steve McConnell?
Consider using Suitable Patterns and Frameworks
It's also worth mentioning the use of a well defined pattern like MVC and build your project with some Framework like Zend, as this will encourage you to put each piece of code where it belongs.

xdebug is a very powerful tool and can help you a lot.
You will be able to see in your development server (and not an ideal server) what is happening with your code!

If you like to improve your php code here are several advices:
do not use procedural programming, use oo
use some framework like kohana
use patterns every time
read some books about java oo programming (good book: beginning java objects 2 edition)
Aldo it is different language, java teaches about good oo code and patterns.
do not use functions with cyclomatic complexity>20
Most programmers use complex hierarchical associative array. They are hard to maintaine. avoid using complex structure of associatve array as DTO, try using classes.
use coning standards.
test driven development, unit tests. If your code can be tested with unit tests you are one step towards good code. Continuous integration is always welcome, but not always suitable in php, depending on the code and libraries you are uning.
use mvc, layers in you architecture
there are a lot more thinks, but keep reading and improve all the time
Regards

Get experienced. Once you have changed a switch statement with instanceof's a couple of times, you see the advantages of polymorphism.
Keep thinking critical of your own code. Keep thinking about how you solve things and be open to other ways.
Read code. Unfortunately, most PHP code is not a good example on how to write code, but you will learn something from it nevertheless.
Read a book. A book is often more in-depth and detailed than any article on the interwebs.

Download a well known open source project or framework like Zend. Then read through some of the code to see how they approach common tasks, and the general structure they use.

Related

Code PHP Correctly, advice for a newb to OO programming

I'm about to start coding a new website. My problem is that I'm still stuck in using old school coding methods.
I recently downloaded some open source code from Question2Answer.org and was really intrigued in how it was set out.
Does anyone know of any sources? or something that I could possibly download, a template or example to help me get started with a new site?
The site won't be anything fancy but I want to start moving into Web 2.0 and OO programming.
In short I want to do it right. Any advice would be appreciated.
It seems like this question isn't getting many answers, so I'll try my hand at it (even though I'd recommend a different language, just because PHP is such a terrible language ). PHP was the first language I ever wrote anything big in, and the one thing that I wish I had known at the time was the MVC design pattern. It has some advantages like:
Separation of logic and UI means less ad-hoc code, more functions (try to follow the "each function does one thing" rule -- It makes things much easier when you go back and look at code)
Functions are easier to verify correctness than huge function-less pages
Functions can be unit tested (do this!)
It's easier to figure out where things are (database logic is in one file, HTML in another, and "controller" logic in another)
Here's a pretty good high-level intro to MVC.
Key points:
The model talks to the database (or whatever other storage you're using).
The view displays things (HTML)
The controller does everything else
I found two good-looking PHP MVC tutorials here and here. Hopefully they're not too complicated, and feel free to ask more questions if anything doesn't make sense.
Good luck!
PS - Don't forget the point about unit tests! If you can't find a way to unit test a function, it's probably too complicated.
There is a reason why people chose PHP as a server-side scripting language. It's extremely easy to pick up and offers many different coding options. Many functions are included without having to know prior importing, and you do NOT have to write OO code if you don't want to.
This all leads to a huge downfall as well, because there are less restrictions on the structure of the code, it's much easier to write bad code.
I suggest using a framework. It saves you time, energy, and the opportunity to write bad code:
CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications. Using commonly known design patterns like MVC and ORM within the convention over configuration paradigm, CakePHP reduces development costs and helps developers write less code.
http://cakephp.org/
http://www.phpframeworks.com/
IMO MVC ( and this OOP ) is nothing really fancy. It's basically a function to register a pointer to a function in an array for example like a hook. This array is looked by another function to do some stuff. A good MVC should have a callback function. IMO this OOP thing is more a bussines logic to help you to monetize your application. It's not really something difficult to understand.

Is there a "right" way to use php?

I have been learning php, by just plugging away at it.
I was hoping someone could point me in the right direction in regards to security, flow and general best practices?
Thanks.
edit--
I suppose a better way to phrase what i am trying to ask is..
What is the best practice:
1.) when processing forms with php, get vs post, $_REQUEST vs $_GET & $_POST
2.) when dynamically creating HTML files (example below)
3.) logins & authentication in the same file as the form creator
4.) Sending e-mail with php
From #2 above
<?php
echo "<h1> Welcome </h1>";
if ($_SESSION['type'] == "admin")
{
//lots of html in the echo statment
echo "tables and admin interface here";
} else
{
//lots of html in the echo statment
echo "tables and user dashboard here";
}
?>
--VS--
<h1> Welcome </h1>
<?php
if ($_SESSION['type'] == "admin")
{
?>
lots of html in the echo statment
tables and admin interface here
<?php
} else
{
?>
lots of html in the echo statment
ables and user dashboard here
<?php
}
?>
--VS--
<?php if($_SESSION['username']): ?>
<p>You are logged in as <?=$_SESSION['username']?></p>
<p>Logout</p>
<?php endif; ?>
ps:
Thanks to everyone who already responded.
Can I also inquire where does a framework fit? I took a class in OOP and we didn't become familiar with any frameworks.
I read lot on the Symfony and zend frameworks but am still confused.
thanks again.
Good programming is irrelevant of language. I suggest you start studying software development concepts such as object oriented programming, design patterns, separation of concerns, reuse, encapsulation, testing and refactoring. Start at any of those and keep "plugging" away at the list and you will get better.
PHP specific - learn the accepted coding standard, such as PEAR's or Zend's. After you've assimilated some of the concepts, pick up a good reference such as one of the top frameworks mentioned in the other answers - Zend Framework, CakePHP, Symfony among others.
The PHP community has never really been strong at offering up any development guidelines or advocating best practices. In the pre-framework days typical php code written by most devs was very amateurish and disorganized - see the Wordpress source code. But PHP is a good language for web apps. It was made for the web and you can write good professional code with it if you want to. It's trendy to bash it but disregard that stuff.
Anyway, like the others have said here your best bet is to use a framework. Being a newbie, it will be important for you to pick a framework that is well documented and has a strong community to help you get over the hump. Here's my rundown of the major php frameworks:
Kohana => a good one but poorly documented with a weak community. skip it.
Zend => the most popular framework for php w/good docs but another poor performer as it's overdone with objects and patterns in an attempt to be overly enterprisey.
Cake & Symfony => are 1st generation php frameworks and also have a rep for poor performance. I'd skip both. A new version of symfony is in the works but not ready.
Lithium => cutting edge new framework led by one of the Cake devs. using php 5.3 and claims to be fast. BUT, not at v.1 yet & also have poor docs at this point => http://li3.me.
Codeigniter => popular, fast, good docs and community. very easy to learn. v2.0 hasn't officially been released but is ready for production use and is php5 only. You can use the same documentation that is on the CI site for v1.7. The versions are very similar except 2.0 drops php 4 support finally. here is the download for 2.0: http://bitbucket.org/ellislab/codeigniter/
YII => Really gaining momentum despite it's goofy name. It's a fast performer with GREAT documentation and a ton of features. A new book is out too. The community is so-so but growing. This framework imo takes a lot from rails. There a web-based code
generation tool and it uses active record. http://yiiframework.com/
you can build apps a lot quicker with YII due to the code-gen and active record but it will be a bit harder to learn than CI. You may find it getting in your way a bit more too as you try to do everything the YII way. CI is more flexible - gives you the foundation you need w/o getting in your way. So for now i'd recommend codeigniter.
good luck!
Use a freely available framework such as:
Zend Framework
CakePHP
CodeIgniter (See comments)
Kohana (From #Alex's answer)
and follow the standards specified by that framework.
Take a look at a reputable open source software, that is known for good code.
Look at Kohana's source, or any of the others from Billy ONeal's answer.
I wouldn't recommend using CI's source as a guide - as I think it still supports PHP4, so some of the code will be useless to learn - unless you plan on writing PHP4 code, which is a bad idea if you are only learning now.
Do not look at WordPress, you will pick up some terrible habits.
Also, while I think of it, learn about OO, and the difference with procedural code.
Why does everyone attack php? Many many excellent sites run off it. At least until they get big enough to merit an overhaul.
99% of the internet is just throw away sites that don't get much traffic, compared to sites like facebook or amazon, so why should they care to learn a language more sophisticated, stable, or strict, if php gets the job done in a cost effective way that is no less stable or secure for what is needed?
Most of the sites I build run off Kohana - a branch from codeigniter. Both are useful. Who cares if CI uses php4. What if you get hired by a web firm that has archaic sites? Guess what - you will need to know php4. That complaint is like saying you no longer need to know tabled html... until you have to design and code a newsletter template for some big company. Then what? Crash course it with google searches?
I say the RIGHT way to use PHP is to follow examples. Yeah wordpress has some awful habits, but it works and is only one of the most successful platforms out there. What does that tell you?
I would say you could learn a lot from a framework like Kohana - and even CI - since both have decent security methods that are not hard to follow. Things like database escaping and xss filtering. It will ween you into OO programming if you are not familiar and both have a decent userbase so you will not get stuck with no answers.
Don't let these guys scare you. for beginners PHP is a good move. Eventually something like Java or objective C will be more beneficial for jobs and application, but learn it when you get there.
It is possible to code well in PHP. Probably the best resource I've seen so far as to just how is here in StackOverflow: browse the questions marked PHP.
In no particular order, some specific things to help you on your way from my years programming in PHP:
Enable Notices and then make sure you don't write code that triggers them. PHP's default install doesn't enable Notices, which is fine for a Production environment, but bad for a Development environment. Unfortunately, their default php.ini file doesn't seem to know which it is being an example for.
Similarly, make sure you have magic_quotes and register_globals both turned off. They are both designed for more simple and naive programming times and today create more problems than they solve.
Initialize variables before you use them. This also means array elements. If your code isn't sure if the variable or element exists, use isset() and array_key_exists().
Pick or develop a sensible coding style and stick with it. You don't need to be frugal with whitespace or linebreaks.
Check for variables you are expecing to be there. This is a tricky one. A great example of this is when processing a HTTP POST that may have a lot of variable elements. Figure out what should be in $_POST and look for that. Don't assume that what is submitted is always going to be what is supposed to be submitted.
Along the same lines, check for the correct values, not the incorrect values. If you need a variable to have a valid value, look for what constitutes a valid value before proceeding, not what might be an invalid value to throw away. For example, if you need a submitted variable to be an integer, then check it's an integer, don't check for a null-string as a null-string isn't the only invalid value!
Separate database access, logic and presentation (this is often called Model-View-Controller programming). Another way of putting that is that you shouldn't be comixing code that is processing ther last POST request with HTML markup being emitted with SQL queries. Most frameworks will enforce this.
If you're not using a framework that provides an Object layer, you will be rolling your own SQL. Either use prepared statements, or use the DB's own quoting function for strings, not addslashes().
It was very easy in PHP 4 to use a lot of memory because structures got copied, not referenced. PHP 5 largely solves this specific problem, but it can still happen with strings. This also doesn't address the tendancy of some APIs to create large structures.
To provide something other than "use a framework" or "look at a framework," here are quick rule-of-thumb PHP-specific practices I've found that make a big difference.
Use PDO and abstract it into a class (or use an existing class). Do not use mysql_query or such functions.
Logic before output. Do not do things such as <?php if($x) { ?> HTML here <?php } ?> (using HEREDOC syntax helps enormously with this).
Use the __autoload magic method to limit includes
These alone would be night-and-day transformation of a lot of ugly PHP code I see. Then there are the obvious language agnostic rules such as consistent naming conventions, self-documenting code, etc.

Rewriting a php app in CakePHP

So, I'm very tempted to rewrite my application using a php framework, as I think it'll make it easier for folks to get involved, as well as improving the design of the app.
CakePHP looks like the best of the PHP web frameworks. Does anyone have any experiences of it? What are the caveats I should consider going from handcoded PHP to using a framework?
Not depending on the framework you'll chose, the first thing you have to know is that :
it'll take some time for you to know it
you'll do crapping things, during that time ^^
so, take into account the fact it'll take some time before you are fully operational :-)
I think those points are the most under-estimated points : using a framework takes not much time... Using it well and to the full extend of its abilities takes... Well, a couple of months, maybe... Which means, when you are at the end of your project you'll say "I should rewrite that with all the stuff I learned while re-writing it the first time" :-D
What it means is : learn what the framework can do, learn how to use it, and use it for a while on small applications, before starting rewriting your big one !
Then, there is probably no "best framework" : one framework may be very well suited for one project, and another one may be best for a second, different project.
I've never worked with CakePHP ; I really like Zend Framework. But that is a personal opinion, and O know people who really like symfony ; they are not wrong : symfony is great -- and I am not wrong either ^^
Still, we sometimes agree on some things ; like the fact that Doctrine (default ORM layer of symfony) is really great stuff, and we tend to use in both symfony and ZF-based projects...
If motivated, you can take a look at many posts on SO, about frameworks... Here are a couple of those :
What PHP framework would you choose for a new application and why?
Is Symfony a good framework to learn?
What, in your mind, is the best PHP MVC framework?
Is Symfony a better choice than Zend for a web development shop (10+) because it is a full stack framework?
Best PHP framework for an experienced PHP developer?
Good luck with those ^^
("Which framework" is a quite pationnating -- and subjective -- question ^^ )
CakePHP has it's good parts but there is no "best" framework. Here's a thread with some clues about what's good in most popular PHP frameworks.
If you never used MVC frameworks before (and Cake is MVC framework) I think you should first familiaze yourself with MVC architecture.
"CakePHP looks like the best of the PHP
web frameworks."
This is subjective. You should compare the pros/cons of other PHP frameworks that will suit your needs.
These posts may help you:
https://stackoverflow.com/questions/2648/what-php-framework-would-you-choose-for-a-new-application-and-why
Why do I need to use a popular framework?
https://stackoverflow.com/questions/249984/php-framework-decision-analysis-paralysis
FWIW, I used it for a time when I was doing some php development. I found it easy to use, and the rapid development aspect was great, and I would imagine has just gotten better in the last 3 years. There is a ton of help in the irc channel, and the documentation is good. I didn't stick around in PHP long enough to become an expert. However, I was just starting out as a programmer then, and ran into Larry Masters (the creator, aka phpnut) and he was just a good person to talk to about design principles, and an all around nice guy. Then again you don't have to be a super nice guy to write a good web framework (I'm looking at you DHH).
Most of the frameworks "bind" you to them, meaning you have to do things their way. If you want to do something they weren't designed to do, you usually have to hack it. For example, how many PHP frameworks currently support Facebook Connect?
Personally I prefer "frameworks" that you can use only the parts you want. Zend is like this, Doctrine and Propel are ORM that are designed to be used with other code. For example, the Symfony framework can use either.
Finally, I haven't found a popular PHP framework that scales well.
I have used cakephp for a couple of projects. From the moment I learned it I have never written php again without it (unless is fun code in which I want to try some new stuff, or learn other design ideas away from MVC). As mentioned, learning it will take some time. How much time it takes really depends on your background. If you have used another MVC framework for a web scripting language then you will learn it really quick; RoR developers will pick it up within hours/days. If you don't have experience with MVC frameworks then it might take you a little bit, but it will really save you time later on the road (including in that project you start with).
Until today, I still learn new things about CakePHP every time I start a new project on it, although I do dig into a lot of its source code (you definitely don't need to do this, documentation and help boards are more than enough).
I definitely recommend you looking into it. It will save you a lot of time and get your head thinking in a different way (if you are not used to the MVC).
Best of luck.
CakePHP's convention over configuration approach has a few advantages once you learn them:
it helps to keep you code organised and understandable
makes it easier for multiple developers to collaborate on the same application
makes it possible for developers to understand other developers' applications
You have two main options when rewriting a legacy application in CakePHP:
change the database schema to reflect the conventions - resulting in less code
code your models to interface with the legacy database - this book goes into all the details
Either way, once you have done the above, it's pretty much plain sailing, and a good learning experience.

Writing Clean and Efficient PHP Code

I have been looking around online and I cant seem to find an article on this that isn't totally outdated. Does anyone have any good articles that give some good advice? What I have read so far is good, and a bit helpful, but I want to have modern code examples, not ones from 2002.
I have coded an extensive PHP/MySQL program and I am trying to make it better now, any suggestions?
EDIT:
People are suggesting frameworks, and I appreciate it but I am looking for coding tips for raw PHP Coding. The whole application is already done and it would be very lengthy to recode the entire thing in a framework.
I will be checking those out for future projects though. Does anyone know or have any tips for Writing Clean and Efficient PHP Code?
Use Smarty
Write to patterns as much as possible.
Edit for the Question Edit
Clean and efficient PHP isn't much different than any other language. Practice good Object oriented principles. Focus on Encapsulation, Separation, and Polymorphism. Refactor often, and Utilize design patterns as much as possible.
There are many sites that focus on these principles. Some use Java, C++, etc. to demonstrate the principles, but it shouldn't be too difficult to convert them over to php.
I'd take a look at the Zend Framework. It is a great framework that encourages PHP developers to use better practices like MVC, OOP etc. If you are not used to this paradigm, I have to say that it will seem daunting at first, but if want to continue with your PHP development I'd suggest downloading it, and start the "Getting Started" tutorial.
There are other frameworks, CMS tools that you can download, but the Zend framework offers are very raw approach to building great PHP applications.
Acorn
PHP Classes helped me a lot (when I was coding PHP). Reading better code usually helps improve my own.
If you haven't already, I suggest making your PHP code object-oriented. It promotes reuse and makes code a lot more readable. Here's a link to show how useful it can be for reducing lines of code etc.
Use CakePHP. It's an excellent MVC framework. Steep learning curve, especially if you've not used MVC before, but the tradeoff is certainly worth it.
Like folks said, frameworks are the way to organize your code best. Many support Model/View/Controller; many are object-oriented already. Try to stick with a PHP5-specific framework (the code will be much cleaner; PHP4 did not support OOP fully). Try to go with the simplest possible templating engine. One PHP5 framework I like that hasn't been recommended yet is called QCubed.
One thing in your post worried me, though - you're saying that you already have the application written, and are now trying to make it "better". If that's the case, trying to switch over to a framework now may be a HUGE (literally huge) task. If this is an application you expect to be in production for 3-5 years, I'd consider taking a plunge; I'd then try to take little pieces of the application and integrate them into that framework environment. Doing it wholesale is a recipe for pain.
For clean PHP code you can use PHP CodeSniffer (search for CodeSniffer on http://pear.php.net since direct links don't work) it's an automatic code style checker. You can define your own codestyle rules and then check the code.
You can even script it, so your code gets checked before SVN commit.

Why use a web framework (like rails) over php?

This isn't a question about what framework to use. I've learned both Rails and Django, and I write all of my webapps in PHP. My question is why bother with the frameworks? It's always taken me longer to use a framework than to reuse old MySQL code and build "models" with phpMyAdmin. I also like writing everything myself, because I know what's going on. I can still reuse functions, etc. and do things how I want, and this freedom seems to be missing from most frameworks.
I'm not saying that my way is right; in fact, I'm trying to figure out where my logic fails. The hype can't be just thin air. What am I missing?
The basic idea of a framework is to allow you to work at a higher level of abstruction and write only the code you have to write to implement your specific requirements. All the other repetitive stuff is handled for you by the framework, and probably with far fewer bugs and security holes than if you did it yourself.
It may feel like it takes longer to learn a framework than to just do it yourself using basic language features and standard APIs, but it's simply not true - not if the framework is good and the app is non-trivial, and especially not once you have learned the framework (using a different one for each new project would of course be idiotic) and factor in the time it would take to find and eliminate all the bugs and correct all the design mistakes that have long since been found, eliminated and corrected in the framework by its developer community.
Almost every developer has cowboy coder instincts that tell him "Doing things yourself is much more fun than using code others have written, and I'm sure I'm good enough to get it right the first time, so it will even be faster and better!". These instincts are almost always wrong.
Frameworks allow you to concentrate on the application itself rather than worrying about the boilerplate code that you'd otherwise have to write for every application. They allow you to structure you site in a much more logical (mostly object-oriented) way, using tried and tested design patters such as model-view-controller. The code in framework is generally more mature and of a higher standard than code you would write yourself for one-off projects as framework have a large community of developers perfecting the code perfecting the code over year. This means that framework-driven sites often perform better and are much more secure.
You also mentioned you like writing things yourself - I know where you're coming from. My solution to this was to write my own framework - I get to reuse and improve my code with every project I do and I know the entire codebase inside out.
Writing it your self may make it easier for you to understand things your self but unfortunately it can make it much harder for other developers to understand what is happening. Frameworks will often be better documented and have a larger community that can support a new developer that is working on the app that you wrote.
I think a big part of it is what you focus on. Frameworks standardize the parts that you shouldn't have to keep revisiting, which helps you focus on the application as a whole. If you reuse your own code all the time you're already using your own makeshift framework.
Your comparing a framework (Rails) to a language (PHP). A framework is going to give you pre-built components so you can spend time on what makes your project unique.
You may already have a code base that helps do this for you. Check out some of the PHP frameworks since that's where you are more comfortable. Take a look at CakePHP, CodeIgnitor and/or Zend Framework.
If you are building many small apps/sites, using a framework may make your life easier.
I think a good step for you is to create your own framework with the code you've programmed so far. ;)
Try to make your code parametrizeable, in other words: create components which you can reuse in different parts of a website (for instance: styled containers), or in different websites (form generators/validators).
You can even go further and create base-classes from which you extend new classes to build your websites. (for instance: data objects with generic select/insert/update/delete methods).
I bet this gives you the best view on why frameworks are so damn handy ;)
It'll take you longer to initially use a framework for the same reasons a PHP developer would take longer to initially use Ruby - you're not familiar with it.
Once you're familiar with them, frameworks can offer the ability to skip the mundane and focus on actually writing the important parts of the app.
You should also just use a PHP based framework like Symfony or CakePHP using them should reduce your production time considerably.
One reason to use a frame work is code separation. Take symfony for example. The model is all done with propel or doctrine libraries. Very little SQL needed. You instantiate a new object and user getters and setters, to store your data, and instead of writing SQL in your page code you create functions in the objects related to the query. When you need to access the same kind of data on different pages you are asking the model for it, keeping the business logic with the model where it should be, so there's never any difference. All the work is done in the "action controller function". You get all the data you need, and then put as little php in the display, basically just echoing the variables you got in the action controller, (with the exception of some for loops and if statements for conditionals. I have found this a more efficient way to code, and on my 2nd project saw the production time cut in half.
You don't need to learn a new language python/ruby just to use a great framework, just have to fin one that works for you.
First, PHP has frameworks too, so the question as stated misses the point.
Yes, you can write your own framework, and as Kris said, there's no shame in that. However, part of the leverage of code reuse is the collective value of the efforts of many. It's not just about reusing your own code. Frameworks encapsulate the common tasks and patterns we all share and provide well tested solutions with many iterations of improvements from the community. No individual effort is going to measure up to that, no matter who you are.
If you roll your own, it will only become world class due to the collective effort of world class people, and that will only happen if your idea merits the attention. The top frameworks out there are already proven on those criteria.
DHH is a smart guy, but the Rails we have today never could have been realized by him alone. Not even close.
If you like "writing everything yourself" as you say, then choose a framework with a core philosophy that matches yours, and start making core contributions in the areas where you can see room for improvement.
Depending on the functions of your Web Application, it can be faster to develop without a framework. For example when the Webapp is just some kind of data viewer.
But as soon as you begin to implement more advanced functions, you are much more efficient with a framework.
Try do do this from scratch:
- proper Form validation
- Handling of multiple Language and Date/Time formatting
- Authentication
See a framework as free tools and stable implemented function for you to use.
Sounds to me like you have already written your own framework in php, since you do mention code reuse.
I can imagine it being easier to use your own set of wheels instead of adapting to someone else's. No shame in that.
Frameworks are there mainly to help people who are semi-new to PHP (or the specific language it is built on) to be able to build a website to an extent that it is secure and easy enough to add on extra parts to the site without having to know a lot about the specifics like security, MySQL (or other database types). In my opinion it is a fairly good way to help break coders into a language, allowing for the fact that the framework isn't too complex of course.
EDIT The reason behind me saying they are for beginners is because myself, as a beginner has used frameworks to break myself into languages a lot better.

Categories