Organising classes - Best practice? - php

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

Related

Mix of PHP functions and classes in one file?

Are there any strong technical reasons not to combine a list of functions and classes in one PHP file? Or combine several classes in a single file?
I have generally put each class in its own file as a way to keep things "clean." And if I needed to be not-OOP, then maybe I group related functions into a single file. However, I've seen code where everything is just piled into one file. Aside from it not being organized, are there other dangers to this practice?
The only technical reason not to do so would be to support PSR-0 (autoloading).
This enforces a one class per file standard. This does not apply to global, user-defined functions.
Separating classes is considered good practice and is enforced if you intend do use any PSR standard.
There is no technical reason not to do this, but you might find you code easier to maintain if things are modular and organized.
Sometimes I need to place a bunch of classes in the same file, usually when i need to declare interfaces for SOAP services or exeptions, anyway, its still "organized" as these 3-line-of-code classes are better off clustered in one file then scattered all over you codebase.
For functions, you should declare them all in one file for the same reason, but if you have a bunch of them (50+) consider grouping them in any way on different files.
The danger is that you're probably making your codebase harder to maintain, organize, and keep version controlled.
The only reason I've seen people try to force every class into one file is that they used something like notepad++ to develop and it made opening files and jumping around classes/functions very slow.
Files in development are a lot like functions/classes and such as that maintenance is easier the smaller and more organized you make them.

Are there performance downsides while using autoloading classes in PHP?

Currently I load in all my classes by including a "all.inc.php" file on every page of my site, this file then goes on to include all the config, classes, functions, etc. that I will use on the whole site.
My issue with this is that often I use classes that only pertain to certain pages/sections of a website, so often I am including a bunch of classes at the start of the page which will not be used.
Obviously autoloading the classes would fix this issue, so my question is, would autoloading the classes give me a performace downside as the server then has to check if a file exists? And if there is a downside, then is this downside worse than having to include a number of classes that may not get used on the page? Or is the difference negatable?
This article has some information and benchmarks: PHP autoload performance (archived). Conclusion:
Autoloading does not significantly degrade performance. Include_path lookup, reading and parsing PHP scripts from disk takes much longer time than that bare autoloading logic costs.
Autoloading a class is almost as fast as including the class in the normal way. Switching to autoloading will improve performance in your case, because PHP loads less files and classes.
Autoloading will improve the performance if the script does not have to search the files each time in the filesystem. If you use namespaces you can have a nice mapping of the namespace and class name to a folder and file like Some/Nice/ClassName would map to Some/Nice/ClassName.php.
If you do not use namespaces and have to search through folders I suggest you to create a custom singleton class to include files that allows you to do something like:
App::uses('Some/Nice', 'ClassName');
In Autoload use the registered path and class name to map it to a path and file combining both args from the uses method in my example. This will allow you some namespace like functionality for class loading until you're ready to change your app to use namespaces.
You should use autoloading with cache index of all available classes/files in project.
Example:
$class_cache=array(
'MyClass'=>'lib/MyClass.php',
'Item'=>'model/Item.php'
);
function __autoload($class_name) {
if(array_key_exists($class_name))
include $class_cache[$class_name];
else
throw new Exception("Unable to load $class_name.");
}
You need to keep class list actual or write some generator for $class_cache.
Each include() and require() (and their _oncesiblings) carry a performance penalty on their own. Disk seeks and reads also come at a cost. It really depends on your code, if you are loading 20 classes but use only 2 or 3 at any single point, then it's definitely worth going the autoloading route.
If performance is your main concern, you should look into merging your class files into a single file and instantiate what you need.
A really old question, but all the answers were actually wrong.
... autoloading takes a significant amount of resources. The number varies a lot and that’s maybe not what you’ve seen in your own app, but a typical 10% wouldn’t be surprising.
from CTO of Blackfire.io, so I'm sure he knows what he is talking about. Read more here

Include all functions in the php file I need or just the functions I need?

So here is what I want to do.
The first option is to write each
function in different php file each
one and then include all of them in
a php file that is called include
functions.php and whenever I create
a new page , let's say index.php I
just include "functions.php";
Why do I need to do that? Because I'll just have to include only one file and all the functions will be included. Now the problem probably will be the server load. I'm not sure how much uncalled functions affect the performance.
The second option is to create again the files I need, team them up and then whenever I need a function just call it. The drawback of this is that I'll have more work to do in order to categorize and I'll have to include a lot of files
So I want to ask, does the first option increase the cpu and memory load that much that I have to go to the second one? Are there any performance issues with the first way or the functions that are not being used are not parsed at all by the php ?
Disk is a slowest part of the server, so in this case variant "all functions in 1 file" will give you little more performance, theoretically.
But I don't recommend you to create "functions.php", better way is OOP. Create classes (objects) with methods, use autoloaders and PSR-0 standard and you will forget about "include" and "require" at all.
This is a time to remember Donald Knuth's famous quote:
Programmers waste enormous amounts of
time thinking about, or worrying
about, the speed of noncritical parts
of their programs, and these attempts
at efficiency actually have a strong
negative impact when debugging and
maintenance are considered. We should
forget about small efficiencies, say
about 97% of the time: premature
optimization is the root of all evil.
Yet we should not pass up our
opportunities in that critical 3%."
In general, your development model should be tuned to match the needs and goals of the project. After you have met the goals, you can always return to such questions as the one you asked. When you do that, your question will probably answer itself. The program structure will dictate the best way to handle your includes.
You may wish to consider using object-oriented programming (OOP) if it is applicable to your project. Whenyou use OOP, this problem may even become a non issue if your objects handle their own dependency loading.

Opinions sought on the best way to organise classes in 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.

Will splitting up included functions improve PHP performance?

I have main php-file with main class.
Also in this class i do
require_once("func.php");
which has many useful functions for my site.
Size of func.php is very big, because there is many functions for different actions on different pages. But I include it on every page, because including called by main class.
What I need to do for optimizing it?
Rewrite func.php to OOP and use in main class something like "$funcs->my_func()"? Will I won some performance? Functions which wasnt called would not occupy memory and CPU time?
Or I must rewrite func.php to many files and call each on specified page?
For example: for "about.php" I will include "about_func.php" with needed functions. But it isnt comfortable I think...
Please, help me :)
And sorry for my eng :)
How big is func.php? Are you sure the size is a problem.
This seems like a performance/optimization question at heart. Are you sure that optimization is warranted? Have you measured your page's performance and proved that including this big function file is to blame for its slowness?
I suggest you answer 1 & 2 to yourself before continuing. If the motivation for your question is cleaner design and modularization, then yes, I would agree that splitting a bug "utils" file into smaller files that share a responsibility or a general area of relevance is a good idea. If, on the other hand, this is a case of premature optimization, then you'd be better off leaving poor "func.php" along (hey, sometimes it's ok to have a big common utils file, as long as it's not hurting you).
Split it into oop classes and use the __autoload function of PHP5: http://www.php.net/manual/en/language.oop5.autoload.php
This wil load the classes only when needed and you don't have to worry about including all neccessary files. It won't give you any performance benefit but it's easier to manage smaller files for one purpose than a big one with several functions which are not dependent on each other.
Do you have a PHP accelerator enabled?
Zend Optimizer
eAccelerator
APC
Because they keep a "compiled" version of func.php in memory which should speed things up, without any code modifications.
Although I recommend OOP, it's not because of performance reasons.

Categories