I have a site which uses the library file lib.client.php which is stored in the php folder in my standard website root and contains a series of classes I have built.
I am going to have to require_once this library file in almost every single page, what is the best way I can implement this? Furthermore, should I be using some conbination of functions using __autoload to accomplish this?
Having seen a very similar question which touches on the issue but offers a very specific answer I can't really use, and looking a bit into the __autoload function, I want to get a more detailed answer for my requirements.
You use __autoload (or better: spl_autoload_register; or even better: some autoloader written by someone else) if:
you have many classes that are being used in different order in different files;
classes are spread across many files;
there is a strict way to tell which class is in which file.
In your case: just use require_once (or refactor, but I would not bother).
Related
I have a "simple framework" whose main instance is $app. Now, what is the best way to implement an autoloader (without using Composer). What I need is to have a class which handles all the autoloading (supporting the various namespaces). I have a few approaches/dilemmas.
At first I thought I should create a "static" class which handles everything. But then something came to my mind. If I use the autoloader before instantiating $app (which contains all the paths), I would need to define the paths outside of $app. And also if an error occours in autoloading a class, I wouldn't be able to handle the error properly (error handler is inside $app, and instantiated after).
Then I thought of dependency injection, making the autoloader an object inside the app. That would resolve the error handling problem, and wouldn't need me to hard code paths or making them globals. But I would have to load many classes (including $app) too before I can instantiate the autoloader.
But really I'm in a world of pain because of this issue, I don't really know where to start, are there some advices I should take into account ? Can you explain me which method should I use and why ?
Thanks.
As a result of the tips I got in this questions, I searched a bit more and found good resources from where to learn.
What's Autoloading ?
Autoloading is basically the process in which the program finds an unknown Class Name and attempts to load it without Class Name being defined. Without an autoloader, this behavior would result in a fatal error (for PHP at least). With an autoloader, things change, and the program will attempt loading Class Name, without knowing where to find it, but relying on functions or classes thought for this purpose, those functions/classes are called Autoloaders.
__autoload() vs spl_autoload_register()
In PHP we have two different ways to achieve autoloading (you might find useful to read it from PHP's site.). The first one is the old __autoload(), the newest is spl_autoload_register(). But what exactly is the difference ? Basically __autoload() is unique, having multiple Autoloaders would cause you many troubles and would get you in solving a problem which can be easily avoided by using the newest spl_autoload_* functions. spl_autoload_register() on the other side allow the program to have multiple Autoloaders by putting them in a stack, in this way the whole system becomes more flexible and much less complicated (having a single Autoloader for different purpose results in having a big unique function handling many requests, this way you'll have less code maintainability and reusability).
Warning: using spl_autoload_register() will overwrite __autoload(), so be careful.
Coding standards (in PHP): PSR-0 vs PSR-4
Let's start by saying that PSR-4 is newer and it was thought to be an improvement of PSR-0, but not compulsory you must use 4 instead of 0, as the standard (PSR-4) states:
It is fully interoperable, and can be used in addition to any other autoloading specification, including PSR-0.
So why should I use one instead of the other ?
Now this is up to you, but as a suggestion PSR-4 solves the "nesting" problem PSR-0, so you should be using the former. Let's suppose I have an application, and my application relies on external components, PSR-0 follows this syntax:
\vendor\(sub_namespaces\)class_name
Where sub_namespaces might be absent. But that translates to a fully qualified path on the hard drive:
path/to/project/vendor/sub/namespaces/class/name.php
Now let's suppose I want to include a library called YourLibrary in my application
\YourDeveloper\YourLibrary\YourFunction
This would translate to
/path/to/project/YourDeveloper/YourLibrary/YourFunction
And here's the problem, what if I want to put that library in a subfolder of mine:
/path/to/project/vendor/vendor_name
PSR-0 is absolute, you can't just modify the namespace to control this behaviour (it would be silly and require too much time) so it would translate to this:
/path/to/project/vendor/YourDeveloper/src/YourDeveloper/YourLibrary/YourFunction
Isn't that extremely nested and redundant ? Well, using PSR-4 you can avoid that and transform that into
/path/to/project/vendor/YourDeveloper/YourLibrary/YourFunction
Without altering the namespaces or the Autoloaders. That's basically how PSR-4 works. This explanation is quite short, but it gives you a glance of why PSR-4 was born and why you SHOULD use it. If you require a more adequate explanation, you can go and read the PSR-0/4 specifications or you can read this beautiful article on sitepoint.
Should I really be caring about standards ?
If you have been in the world of programming for enough time, you probably won't end up asking such question. But if you are, you are probably a new programmer, or you haven't been a programmer long enough, that's why you SHOULD read this answer.
In the IT world, and especially in programming, standards are almost everything. If we hadn't followed standards, we might not even have videos on our computers. If anyone follows their own standard, everything would look messy, and in this case, Autoloaders would become personal; so instead of having one SIMPLE Autoloader, you would end up having many Autoloaders, one for each standard, making your application much more difficult to maintain and to debug (because everyone can make erors).
If you writing a framework you should always look at existing ones, which properly allready solved your problem. Then you get inspired or just use that component. A great starting point is symfony, their components are seperated and tested. If you load it with composer or download it manually is your choice ;)
They also have a Classloader http://symfony.com/doc/2.0/components/class_loader.html which you could use as it. Or you just take a look what their approach is.
The Autoloader (or your classloader) should be the included at the beginning of your application and this should be the only class you include directly.
If you want to load your class dynamic your have to take a look how your store your classes, there are diffrent "standard" ways like PSR0 http://www.php-fig.org/psr/psr-0/. If you want your users to add their own classes, when they using your framework you should consider to support multiple standards.
I not sure where I heard this, but I heard/read a little while ago that:
"Classes are not recommended in small php applications/scripts, as they need to be called on each request."
But isn't this the same as calling functions on each request?
Also, how do you include several classes into a application/script, as I have seen that people have a simple file that include all the classes.
Isn't there a better way to include all the classes into a application/script?
Cheers!
As you can not even give source of the comment, I suggest to drop it completely because it looks like that it is totally indifferent and therefore a waste of time to deal with.
This should lighten up to answer your actual questions as well:
But isn't this the same as calling functions on each request?
Not the same but quite comparable, right.
Also, how do you include several classes into a application/script, as I have seen that people have a simple file that include all the classes.
Isn't there a better way to include all the classes into a application/script?
Define better? What's wrong with that approach? Generally spoken, there are many ways how this can be acomplished, however it relates to how the classes are organized in files and then how the files are organized in the file-system.
Normally you include the file's classes on need, either manually or by using an autoloader. And that's pretty much is it. See the links on the right side you will find tons of information.
As yes123 says, that quote doesn't make sense. It is up to you as the developer to decide how your project should be coded and whether or not it should use classes.
There are several schools of thought on how to best include classes. Personally, I prefer to have a seperate file for each class, the file having the same name as the class, so a class called mySuperClass would be in a file called mySuperClass.php and included with require_once 'mySuperClass.php';.
Other people like to put their classes into files containing several related classes. I don't think it matters so long as you decide what you want to do and you're consistant about it.
You may want to look at autoloading too and class/file naming conventions such as PEAR. I use Zend Framework for most of my projects, so tend to stick with autoloading and the PEAR naming convention. http://framework.zend.com/manual/en/coding-standard.naming-conventions.html other people will have their own preferences for this.
PHP 5.3 has also introduced namespacing which gives another approach, there is an introduction to it here:- http://www.sitepoint.com/php-53-namespaces-basics/
I haven't really taken to that as I quite like my current system, but it may suit you.
you can use __autoload. It will include class when it need
function __autoload($class_name) {
include 'classes/'.$class_name . '.php';
}
I have this problem that is really causing me headeches whenever i'm designing my apps in php: I don't know if i should create separete files for each function(e.g.: functions for validating specific forms).
OK, one would possibily argue that this makes no sense because I would have to include each file separetly and this would result in a more slow application maybe?
But I still think it does make sense since for one pageload i doubt that other functions would be used by the script at all, so they must be loaded just for nothing? besides, i don't have to include each function-file manually if the system i design does this dinamically (parsing url vars or such) for me, that is, loading function(-files) exactly when needed. What do you think?
The overhead in file includes is minimal, you shouldn't have to worry about it really, considering caching and other things. Of It's more about how you can keep yourself organized and find your stuff quickly.
Honestly, I rarely use functions, I use classes. The rule is usually to have a class per file. But I also have a toolbox file that contains all my global functions.
Are you using OO? If so, then you should definitely keep it one class per file, and name the files intelligently...
class Page {
...
}
should be findable somewhere like classes/Page.php or includes/Page.class.php or similar.
If you just have a bunch of global functions, you should group them in files, e.g. includes/functions/general.php.
To elaborate, your functions folder may have...
array.php
string.php
form_validation.php
request.php
general.php
html.php
If you are organising your files like this, a better idea is to use a class and make the functions static, e.g. string::isAlphaNum($str). This is a better idea because it only introduces one new term to your global namespace, instead of a bunch of them needlessly.
If you are using PHP 5.3, you could also look at namespaces.
You should just make sure that you have APC, xCache or eAccelerator installed. All of them provide cache for compiled PHP bytecode.
It means that once the file has been included it will be stored in memory and ready to use by feature requests. There won't be any need to include files.
You will almost certainly see a more significant performance hit through increased disk I/O reads on (many) multiple file includes than for smaller set of files with many functions.
For automatic file includes, wrap functions into suitable classes and use spl_autoload to let PHP handle the include process.
I'm trying to find the best pragmatic approach to import functions on the fly... let me explain.
Say I have a directory called functions which has these files:
array_select.func.php
stat_mediam.func.php
stat_mean.func.php
.....
I would like to: load each individual file (which has a function defined inside) and use it just like an internal php function.. such as array_pop(), array_shift(), etc.
Once I stumbled on a tutorial (which I can't find again now) that compiled user defined functions as part of a PHP installation.. Although that's not a very good solution because on shared/reseller hosting you can't recompile the PHP installation.
I don't want to have conflicts with future versions of PHP / other extensions, i.e. if a function named X by me, is suddenly part of the internal php functions (even though it might not have the same functionality per se) I don't want PHP to throw a fatal error because of this and fail miserably.
So the best method that I can think of is to check if a function is defined, using function_exists(), if so throw a notice so that it's easy to track in the log files, otherwise define the function. However that will probably translate to having a lot of include/require statement in other files where I need such a function, which I don't really like. Or possibly, read the directory and loop over each *.func.php file and include_once. Though I find this a bit ugly.
The question is, have you ever stumbled upon some source code which handled such a case? How was it implemented? Did you ever do something similar? I need as much ideas as possible! :)
One way you could pull something like this off is to put those functions into classes and then set up an __autoload function. If you are against wrapping the functions in classes than this solution probably won't apply to you. Personally I like it because it allows me to namespace my functions and share private methods between them.
First you set up your autoload function similar to this. You'll want to adjust the naming convention to fit your own style, and probably introduce some error handling, but this is just to get the basic idea across.
function __autoload($class_name){
require_once(strtolower("library/$class_name.class.php"));
}
Then anywhere in your code regardless of scope you can do something like this.
arrayFunctions::doStuff($myArray);
PHP will automatically try to include "library/arrayFunctions.class.php" and look for a method called "doStuff" in the arrayFunctions class.
I have issues with this idea. Hitting the file system to include a single function is very expensive in the terms of it lowering your max possible requests per second.
It's generally much better to load/parse five functions in a single file (static class?) and only use two of them (one stat call) rather than load two files for two functions (two stat calls).
Which obviously becomes even worse when you need all five functions.
To automatically load stuff when need, put your functions in classes and use autoloading.
For the name conflict, use namespaces (if you have PHP 5.3).
How do you manage your php codes? Do you prefer functioning within one php file or including larger blocks of "raw code"?
Edit: In fact, my code is pretty nasty, as I don't use any namespaces and classes - only functions and including. I shall look the classes up ^^.
Use them as you need them.
I use include for chunks of big code doing processing, and functions for "utility" functions. Sometines i use includes within function also... it really depends on how clean you like your code.
Think that many includes means more fopen() from the PHP module, and those can slow doewn the whole script execution..so dont try and put too many includes though.
If you are using php classes, this will sort itself out. If you are not, then it's really hard to give an acceptable answer, except that you should learn to. All php code I've seen done either way without classes seems to become quickly messy.
I agree that OOP is the way to go. Large solid blocks of code are nightmare for maintenance. Definately not the way to go. You should split your code into small blocks that interact with each other and are easily maintanable on their own.
When I used to program in PHP I liked to group general utility functions in a common file to include in most of the pages, and group classes in dedicated files, to load them only when needed.
I typically use functions/classes for logic and includes for display. I end up with something like this in a controller...
case 'widgetlist':
$widgets = $DAO->getWidgets(); //get some query
include('view/showWidgets.php'); //assume a global $widgets variable
break;
I have found it easier to give an HTML/CSS designer an include rather than a function call which displays. The down side is that I rely on globals to pass variables to the include rather than arguments which are much safer.
I make classes in separate files, with the correct prefixes as namespace (until they are included at least). I also put functions as static methods in "static classes" for the namespace effect.
I use autoload to include the files so I don't have to write a hundred includes.
Save My_Example_Class as {lib}/My/Example/Class.php
The thing I'm working on has one included file at the top of every page that contains all the global functions and database setup stuff. It works as-is but I'm now moving the functions into separate files, because with everything in a big lump it's completely impractical to do any testing.
PHP has an __autoLoad () magic function that you can use to intercept class calls. If the class doesn't exist yet, you can setup some simple code to go and look for the proper class code to include. It will then continue to execute as normal.