views:

1718

answers:

9

Please share your favorite application design / design patterns for use in PHP with me. Some things I'd like to know:

  • How your folders are designed
  • How you use object oritentation in your PHP applications
  • Do you have a standard way of dealing with CRUD, pagination, or any other common tasks?
  • How do you avoid using repetitive code? What's your approach to libraries/sharing common code, etc?
  • What are ways in which you can make your code more elegant?

You don't have to answer all of these, answering any or a few of these will be helpful.

The reason I'm asking this,is because I'm very tired of writing repetitive, ugly code in PHP and I want to make a small framework for my freelancing projects which will make programming easier and let me focus on the challenging/business tasks rather than form validation, pagination, and the other mundane activities which make up 80% of programming work in PHP

All opinions appreciated!

+7  A: 

I almost feel like a broken record, but I would recommend that you take a look at some of the common frameworks for two reasons:

  1. Even if you choose not to use one, some of them are very well written and very well designed. I particularly like Zend Framework but I'll come back to that in a second.
  2. Ask yourself why you're reinventing the wheel. Do you really feel that you understand the same design problems everyone else faces so much better than the community behind (insert framework of choice here) to justify writing something from scratch? Speaking as one who originally looked at several frameworks and decided that they were too big, presented too much of a learning curve or too much overhead and so developed my own, I can tell you that writing your own from scratch is a big pain if you can simply use an existing one that can be easily extended.

Speaking of using a framework that can be easily extended, I have had very positive experiences with Zend Framework. It's cohesive and yet loosely coupled structure makes it possible to quickly and easily extend any existing component and the entire framework is designed around the idea that you will need to write your own helper and plugin classes to add to its overall functionality.

I've found Zend Framework to be so completely flexible that I am running a single website as part Zend Framework MVC and part my old crappy framework and even older crappier code that I haven't gotten to rewrite yet. In fact, because during our rewrite we found one page that ran unacceptably slow using the old framework, I've switched the single page to run under the Zend Framework architecture.

To answer some of your questions, I would recommend that you look into Patterns of Enterprise Application Architecture by Martin Fowler. He provides a lot of valuable insights into how to solve a number of these common problems like how to create a database interaction layer in your application. Fowler also covers topics like MVC and Front Page Controller.

Noah Goodrich
+1  A: 

i've explained most of my PHP methodology here.

but nowadays, i just use Django everywhere i can.

Javier
+2  A: 

I started out with the smarty templating engine when i first got tired of mixing code and html. After hacking for a while, I realized that writing my own framework is just duplicating work.

I've done a few projects with Joomla, which is really a CMS but it gives clients a lot of control over content.

Ultimately I've settled on using a real framework for my projects. I'm using symfony, which is inspired by Rails and is very well documented, but I've heard cakePHP and ZendFramework are also very good.

vishvananda
+9  A: 

I have to agree with the above posters. If you're not using a framework when programming in PHP you're really programming with your hands tied behind your back. I personally recommend CodeIgniter. It's the fastest framework around, it's very easy to learn, and has a very active community. All of your questions will be answered by the framework:

* How your folders are designed

CodeIgniter (or any framework for that matter) separates your logic into views, models, and controllers, each with their own folder.

* Do you have a standard way of dealing with CRUD, pagination, or any other common tasks?

CI has a pagination library, and it has 3rd party libraries like DataMapper for wrapping your CRUD calls in an object oriented way (ORM).

* What are ways in which you can make your code more elegant?

The seperation of the model, view, and controller make for very elegant code.

(The 2 questions I didn't answer are pretty much implied when using the framework)

ryeguy
+2  A: 

I use Zend Framework, which pretty much defines folder layout and OOP (MVC paradigm). For common tasks, such as for example pagination I use Zend_Paginator (my model classes implement Zend_Paginator_Adapter_Interface), for validation I use Zend_Validate classes etc. Thanks to that I can fully concentrate on business logic instead of reinventing the wheel.

vartec
+7  A: 

I imagine a lot of php developers have followed a similar route to mine: small scripts -> procedural/inline-code -> possibly a look at templating -> OOP -> then a framework. I think it may be quite common for a PHP developer to have "grown up" with PHP, learning design patterns to match the features available with the current version.

MVC is the most frequently used design pattern in the popular frameworks being used today. CakePHP is my framework of choice although Symphony and Zend are very popular too – it's well worth trying out a few and it'll soon become apparent which you feel most comfortable with.

For most projects (where rapid development and portable code are the priorities) I use Cake, however for light weight apps (one I developed recently was Good Baad) that you'd like to run fast (on low spec hardware) and do not need the bulk/weight added by the functionality of one of the large frameworks I recommend reading Rasmus Lerdorf's article on his No Framework PHP MVC framework.

Basically if you're after a true object oriented language that encourages beautiful code and the best design practices PHP is always going to lose out to the likes of Ruby Python and C#. But, PHP has its strengths e.g. no need for a templating language (it is one), PHP can run very fast and cheaply and does not need the weight of a large framework for all applications.

I'd encourage adopting a design pattern that takes the manageability of a design pattern like MVC and combine it with PHP's strengths.

Rudenoise
Have you tried codeigniter?
Click Upvote
Yes, but I didn't take to it - while I like the small footprint I didn't thin it went far enough. I like the conventions and restrictions of Cake and Symphony - and for rapid development these are perfect. For light weight apps I think you can go lighter that CI - it sits in no-man's land for me.
Rudenoise
+2  A: 

Using Zend Framework and Doctrine, my folder structure usually looks like this:

root
  app
    config         (db config, routing config, misc config)
    doctrine       (fixtures, migrations, generated stuff, etc)
    lib
    logs
    models         (doctrine models)
    modules        (zend mvc modules)
    bootstrap.php
  docs             (db diagrams, specs, coding standards, various docs)
  pub              (web root)
  tests
  tools            (console tools, i.e. doctrine-cli)
  vendor           (zend and doctrine libraries, preferably as svn-externals)
Karsten
+19  A: 

I might get voted down for this, but if you really do want to write your own framework, I say go for it because you will learn a lot from the experience. The other frameworks mentioned here are great and tested and you wouldn't be making a bad decision using them, but it's your choice.

Before starting to write your framework, look at the other frameworks (at their syntax, directory structure, naming schema, design patterns, etc) and try to figure out why they did what they did and what, if anything, you would do differently. Try out a few tutorials and play with their code, make a few sample apps. If, after doing that, you don't like using them, then go ahead and start planning your framework, keeping what worked and improving what didn't.

If you do decide to roll your own, here are a few things I would recommend from my own experience:

  • Make Security Your Top Priority - If you write a data access layer, use bound parameters. If you write a form class, guard against CSRF and XSS. Catch your exceptions and handle your errors. Make sure that your PHP environment is secure. Don't try coming up with your own encryption algorithm. If you don't concentrate on security, it's not worth writing your own framework.
  • Comment Your Code - You will need comments to help you remember how your code works after a while. I usually find that docblock comments are more than enough. Beyond that, comment why you did something, not what you did. If you need to explain what, you may want to refactor.
  • Single Responsibility Classes and Methods - Most of your classes and methods should do one thing and only one thing. Especially watch out for this with the database - Your pagination class shouldn't rely on your data access object, nor should almost any other (low-level) class.
  • Unit Test - If each of your methods does only one thing, it should be far easier to test them and it will result in better code. Write the test first, then the code to pass the test. This will also give you greater freedom to refactor later on without breaking something.
  • Abstract Similar Classes - If you have more than one class that does similar things, create a parent class that uses the similarities between the classes and extend it.
  • Delegate and Modularize - If you're writing a validation system (and chances are you probably would), don't include each validator as a method in some super validation class. Separate them into individual classes and call them as needed. This can be applied in many areas: filters, languages, algorithms, validators, and so on.
  • Protect and Privatize - In most cases, it's better to use getter and setter methods rather than allowing direct access to class variables.
  • Consistent API - If you have a render() method and a draw() method that do the same things in different classes, pick one and go with it across all classes. Keep the order of the parameters the same for methods that use the same parameters. A consistent API is an easier API.
  • Remember Autoloading - The class names can get a little clunky and long, but the way Zend names the classes and organizes the directories makes autoloading a lot easier.
  • Never echo or print anything - Give it as a return value and let the user decide if it should be echoed. A lot of times you'll use the return value as a parameter for another method.
  • Don't Try to Solve the World's Problems - Solve your own first. If you don't need a feature right now, like a class for localizing numbers or dates or currency, don't write it. Wait until you need it.
  • Don't Preoptimize - Build a few simple applications with your framework before fine tuning it. Otherwise, you can spend a lot of time on nothing productive.
  • Use Source Control - If you spend countless hours creating a masterpiece, don't risk it getting lost.
VirtuosiMedia
I disagree with the single responsibilty part, it sounds good in theory but making the pagination class do the querying to find the total rows, etc using the db class is a lot better than rewriting thixs code each time. Other than that great answer
Click Upvote
Thanks. :) The reason I mentioned that specific example is because then it allows you to paginate more than just database information, so if your data is stored in any type of array or even an XML file, you can still use the pagination class.
VirtuosiMedia
One example would be if you wanted to paginate an RSS feed. Of course, part of this would also depend on how your data access layer works. For mine, I don't just pass in a fully written query to my DAL, so handling the db in the pagination class wouldn't work for my personal implementation.
VirtuosiMedia
+1 for placing security first, and qualifying it well
Jens Roland
+1  A: 

I've been messing around writing my own stuff for a while now and everytime I can never get around to finishing it fully because I get stuck on something.

And then comes the part where I come to realization of whether I am doing something right.

And as such I have given up on writing my own an going with a crowd favourite: Zend.

I looked at others but it seems Zend has been around a while and they know their things.

MVC is also the way I am going forward with anything I write now.

Gautam