Opinions sought on the best way to organise classes in PHP - php

I am pretty much set on using the Java package naming convention of
com.website.app.whatever
but am unsure about the best way of doing this in PHP.
Option 1:
Create a directory structure
com/
mysite/
myapp/
encryption/
PublicKeyGenerator.class.php
Cipher.class.php
Xml/
XmlHelper.class.php
XmlResponse.class.php
Now this is how Java does it, it uses the folders to organize the heirarchy. This is however a little clumsy in PHP because there is no native support for it and when you move things around you break all includes.
Option 2
Name classes using a periods for the package, therefore names are just like in Java but can all be in the same directory making __autoload a breeze.
classes/
com.mysite.myapp.encription.PublicKeyGenerator.class.php
com.mysite.myapp.encription.Cipher.class.php
com.mysite.myapp.xml.XmlHelper.class.php
com.mysite.myapp.xml.XmlResponse.class.php
The only real disadvantage here is that all the classes are in a single folder which might be confusing for large projects.
Opinions sought, which is the best or are there other even better options?

You could follow Zend Framework standards like
Option1 with autoload
new App_Encryption_Cipher
in autoload magic callback replace the _ to '/' and do further checking (the file exists? garbage in the filename being seek? symbols?)
This is however a little clumsy in PHP because there is no native support for it and when >> you move things around you break all includes.
Depends on how you plan/design your application. there is no escape when it comes to refactoring anyway :)
I know you are used to java naming conventions, but if you do something like (new com_mysite_myapp_encryption_cypher) well, it kinda becomes a pain to write all the time

It depends not only on how many classes you're going to have, but also how many sites and apps you will have. If you have more than one site or app, it would be more logical to have folders so you don't get confused. If you only have a few classes (say less than 20), it might be more logical just to keep them all in one folder. Based on the kinds of classes above and how detailed you want to be, I'd go ahead and use directories so that later on you don't look at it and say "Gosh I wish I had used directories". Then you end up writing useless programs that you'll only ever use that one time just so you can change your file structure.

I would suggest Option 1, because in that layout in particular is the separation of codes, which will end up as a much manageable and flexible system.

I've always preferred prefixed files with fewer folders so there is less navigating around, but it is just my personal preference.
if you think you might want to change it later, you can create a central include script like:
<?php do_include('encryption_cypher'); ?>
function do_include($file){
if($file== 'encryption_cypher')
include('class/app/someotherfolder/encryption/cypher.php');
}
However, this is just messy in the long-term, so pick the lesser of the two evils and go.

Related

small php project is now a huge mess (inside)

I started a small project for me and a few friends to edit a few tables in a multi-database (mysql). Now the project is over several hundred pages and while it looks incredible on the ouside, it is stating to feel cluttered inside. no structure. here is what we have:
3 databases
several hundred tables make up the three DB.
The php project is designed to make it easy to edit these tables instead of manually.
does anyone have a suggestion how to organize the code. I a starting to see repeated includes at the top of files, certain code is starting to repeat (I have functions for the more common ones)
I would like to stay away from "CLASS" type programming (unless you feel this might be best) only because it is an open source project and some of my friends are not that great at php, so want to keep it simple. but for organization, I could go to class style.
my biggest concerns is that the majority of pages (the html part) are tons of cut and paste. so each page is like the other. not sure how to consolidate those efficiently. I think once that part is figured out, the php code will trim up as well.
thanks
I'd go for the Object Oriented style here (or class type programming as you said :)). This will cut your code massively, it will also help if you need to change a function which is on multiple pages rather than changing multiple functions.
Your friends will thank you in the long run, especially when they embrace the goodness of OO.
If you mean "CLASS" as in OOP (Object Oriented Programming) it's definitely something you should consider. Arranging methods in objects is very convenient once you get used to it, when you have discovered the autoloader you'll know why.
You should also take a look on the market of MVC frameworks. MVC stands for Model, View and Controller and is a fairly common pattern amongst applications. I'd recommend looking at CodeIgniter which is very easy to get started with, even without an extensive PHP career.
If you by any chance would stick to the 100% interpreted, in other words: spaghetti and functions. I'd split everything in to files grouped by their area of functionality. Like: media.php, database.php et.c. Take a look at WordPress and the wp-includes folder and see how they've solved it. Good luck!
There are a lot of things you can do differently here. Here are three to get you started:
You're going to have to move to object-oriented programming, especially if you're wanting to go the route of code organization. Keep with the DRY principle at all times.
With that in mind, check out a good frameowrk. I would recommend CodeIgniter. The MVC design pattern will remove a lot of the redundancy in your code if you use it correctly. If you choose to not go down the framework route, I would definitely look at some templating libraries to help you out.
Normalize your database. This will help you remove redundant model code.
My suggestion is to use a XML-like abstraction layer for all the database fields and also use OOP where you can and understand. You can use XML-File-configuration to separate the database-logic and you can use the php XML-extension to parse it. Now if you have your XML-tree in the memory you can parse it again with an engine to output the html stuff. I use this a lot for example TYPO3 uses this too, but not a XML but a very large array. And also using this you can create your own XML-language and attribute. It's a bit like XLST but not as deep but it's better then TYPO3.

Organising classes - Best practice?

A quick question about best practice with PHP classes. I have seen people use filenames such as something.class.php to organise their classes in external files.
So, is it best practice to have one file per class, or multiple classes per file.
At the moment, I am scripting an RPG and have a single class_lib.php file. I currently have just character-related classes in there, and before I go any further would like to know if it's more suitable to keep classes grouped in files, have all classes in a single file, or keep each class to its own file.
What are the advantages/disadvantages of each approach?
Made this CW as it may not have a definite answer
Their are pros and cons of both approaches. Separating classes into separate files allows you to instantly know which file to modify if you need to update a class and keeps all logic related to that class in the same place. It is also beneficial from a source code repository standpoint to separate files. It increases the amount of load to include a ton of files, however this is most likely negligible. Another disadvantage is having to open numerous files to in the course of coding and it can be a pain to navigate if you decide to use folders in the structure as well.
Having related classes in the same file is more convenient than anything and can be confusing to figure out which file holds the class you need to modify.
If your project won't be terribly large it will most likely be up to you on how you want to organize it. But think about it in terms of "If I don't touch the code in 6 months, will I remember where to go to edit this class?"
One file per class, with autoload to include them only when they're needed
Keeping classes in separate files allows for autoloading. Conceivably, it might help with performance if some classes--which you would otherwise put in one big file--are used rarely (N.B., this is just blind speculation. Autoloading itself might incur an offsetting performance cost.)
It depends on taste, and the sizes of your classes. The separation is purely for organization. So, if you think it would be easier in one file, or one class per file, depends on you.
Advantages: easier to find what you want. Less scrolling!
Disadvantages: constant switching between files. May be annoying when making new classes on the fly.
One class, one file. IMO, it's easier from an organizational point of view.
Other tips:
Keep levels of inheritance and parameters list to an absolute minimum. Any more than 5 or 6 becomes a bit too complex
Use the most restrictive scope qualifiers

What should be the standard PHP code file lenth in LOC?

I do PHP coding a lot in my company and personal work. Usually my files get bigger, sometimes more than 2000-3000 lines long. Then, they get difficult to manage.
My Question: What should be (is) the standard length of a PHP code file in terms of lines-of-code. At what length do you guys split it up?
Note: No Object Oriented programming (I don't use classes). Please answer accordingly.
Clarification of not using classes:
I do use functions a lot.
I don't use classes because the code is legacy. I have to maintain that and add new features.
I was a C programmer before. So, going OO is somewhat tough for me. Like learning whole new way of doing things.
There is no good standard length. Some files grow bigger, some smaller.
A good guiding principle from Object Oriented Programming is separating tasks and concerns into classes, and splitting those classes into separate files.
That is the most logical separation, and allows using PHP 5's Autoloading. The basic principles may be worth adopting even if you don't want to get into serious OOP.
Related questions:
What are the advantages/disadvantages of monolithic PHP coding versus small specialized php scripts?
Code should not be split according to number of lines of code, it should be split according to functionality. Parts of your code that handle, say, templating, should go in different files (and possibly directories) than parts that handle, say, authentication. If you have a file that's thousands of lines long, it's almost certainly doing way too much and needs to be split up, if not refactored entirely.
Maybe you should start using classes then.
BTW, I definitely split the PHP code files at 1000 lines of code.
Use classes and OO programming. I have been to an workshop once "make love to your code" that stated to avoid functions that are longer as the space on your monitor (you should not scroll to look at the whole function)
Even quite large code files can be reasonably easy to manage if you organise them well. You should keep your functions short, keep related functions together, and name them well.
You will also find it easier to manage if you use an IDE with a function lookup table - I use Netbeans, and on the left hand side it gives me a panel with quick links to all the functions in my current file. It also gives me the ability to click on a line where a function is called and jump to the declaration (anwhere in the project).
On the other hand, if you have code files several thousand lines long which consist of a single function, then yes, the odds are it will be very hard to manage, an no amount of IDE cleverness will help.

Is there such a thing as an over use of PHP's include()?

I am using includes to pull in the various functions I am using, and I am now starting to use include to pull in chunks of HTML/PHP. Is there a point where I have overused includes?
As soon as you start having problems reading your own code that you wrote some time ago, it's definitely too much.
I recommend programming in object oriented PHP and using autoloaders to avoid include/require as far as possible. Excessive use of include/require often leads to unreadable and unmaintainable spaghetti code, which is very bad.
In small projects I usually just have one require statement to pull in my autoloader function(s) and in larger applications I use Zend Framework where I rely on Zend_Loader exclusively.
From a purist point of view I'd say: More than 3 includes/requires in your own code (without third party libs) is too much:
One for inluding some iniitialization stuff
One for loading the autoloader class/function
And the one in the autoloader itself. There should only be one function that actually incudes/requires files. That function or method can then be reused in extended autoloader classes.
I mostly try to stick to that principle.
I'd say it depends to what point your code is still readable. If someone not working on your project have difficulties to understand your code then yes, includes are overused.
You can overuse anything but it's probably not doing you that much harm (just a few extra stats here and there). You have to remember that large projects like Drupal and Wordpress do hundreds, if not thousands of includes.
If you're hooking in HTML, you might be getting a bit desperate. I'd personally have a good look at a proper templating language or even a framework that helped you into a MVC or MVT stance. It makes maintaining it a lot easier than chasing includes all over the place and (more importantly), keeps 95% of your logic out of your presentation files. Oh and they can maintain your databases in a much more programmatic modular method.
Basically Frameworks give you a lot of development benefits ;)
Symphony and CakePHP are both good frameworks but if you just want a look at templating, have a go with Smarty.
If all you are using is includes then I would look into another way of doing it.
For example if you have a separate file for every function maybe look into putting them all in one file or putting them with similar functions.
It's really a matter of architecture and optimisation. Rather than discuss what's the optimal number of includes per script, I'd advise using a template engine, e.g. Smarty because it allows you to:
Separate markup from the program logic
Use template tags and built-in functions to considerably ease the development
Cache preprocessed PHP files making the whole thing a lot faster for your users

Building cms for my bachelor degree and need some advice

I'm currently starting to write my own CMS in php from ground up using CakePHP (or should i use something else?) for my bachelors degree. And i'm thinking about various stuff that will be needed to do.
One of the things i can not figure out is if i should use a single file (for example, index.php will handle everything, and will include everything) or i should break up my cms into a few smaller files.
so my main questions are
is cakePHP a good choice?
use one file for everything or use multiple files?
do you have any good general advice on building more complex websites using php or any best-practices advice (i don't really understand why they don't teach us this in school)
Using a single entry point or multiple entry points becomes a moot point if you are using most frameworks. CakePHP for instance has an index.php file and all you end up doing is defining models, views, and controllers for different parts of your project. I would imagine that most frameworks these days work this way.
Alternatively, if you choose to roll your own framework and system for managing this, which given this is for a bachelor's degree may be (1) a lot of extra work but (2) more revealing and more instructive, I can speak from experience that I found having a single entry point to be useful.
It enables you to have a common code path for set-up stuff: things like enabling E_STRICT, E_NOTICE, etc. for debugging and reliability purposes. Things like sanitizing form inputs to work around the magic-quotes setting. Yes you can do that from an include 'globals.php' but:
Putting everything in one place also lets you come up with a standard file-naming convention and an __autoload handler that will help remove any include or require directives except for perhaps one. Means you can add classes and such without having to also remember to update a master file.
And this is entirely subjective, but I have found that it's easier to create simpler URLs using this. Instead of /volunteers/communities.php?id=Hedrick_Summit I can do /volunteers/communities/Hedrick_Summit which is more pleasing to me.
As for the choice of CakePHP, I have briefly toyed around with that framework. What I don't like about frameworks in general is they often have to be too general, to the point it results in extra cruft and slower page rendering. And the moment you have to do something that pushes the boundaries of the framework, and you will, you end up fighting the framework.
But to be fair, CakePHP seems to be adequate and generally well-designed. I personally took issue with the ORM layer but that was me striving for perfection and actually trying to do work in the SQL query. It has a reputation for being slow, but unless you're trying to build the next Facebook you should be fine.
Using a single file "entry point" gives you more flexibility when it comes to routing requests to various logic - you'll only ever have to worry about filtering one spot in a request chain.
These are really subjective questions.
I, once, wrote a CMS in php from ground up for my 3rd year project.
What I did was basically:
Checking how other people did it (Plume CMS and CMSmadesimple were a good start)
I didn't use any framework (that was a requirement)
and Yes, I used index.php with multiple params to handle different pages.
Answer is yes use multiple files in multiple directories, it makes all difference in the world when you need to debug or scale.
I would advise you to keep in mind the MVC (Model-View-Controller) pattern.
It is one of the most commonly used (and often misused) patterns in the CMS field.
Also, don't be afraid about looking what other people are doing. Read the code from Joomla, Drupal and other open source CMS. Have a look to language different from PHP to have a comprehensive glance about the possibilities.
Don't try to simply re-invent the wheel. Even if this is simply a Uni assignment, try to put something new on your CMS. Something that would push me to use yours instead of other CMS.
is cakePHP a good choice?
That's a highly subjective question and as such unanswerable. Though, if you want to experiment with architecture (eg. compare front controllers to page controllers), you probably should build more from scratch, as a lot of those decisions have already been made by the writers of said framework (And a lot of other frameworks, for the matter).
use one file for everything or use multiple files?
It's called a front controller (single entrypoint) or page controllers (multiple entry points). Get a copy of Patterns of Enterprise Application Architecture by M. Fowler.
do you have any good general advice on building more complex websites using php or any best-practices advice (i don't really understand why they don't teach us this in school)
There are billions of CMS's. Find some of them and analyse them to find out what they did and how they differ from each other. Trying to categorise the different approaches and compare their strenghts/weaknesses could make for a good paper.

Categories