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';
}
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.
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.
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).
I have a problem regarding the filenames management in my PHP project.
If I have a large number of PHP files in my project and I rename a PHP file then this will result in changing the name of file everywhere where I used the old name for that file.
I have adapted a solution to this approach but don't know if it is effecient enough (want to know if there is another approach or solution available?).
The approach is as follows:
create a php file which has define statements like this:
define("FILENAME_ADD", "addfeedback.php");
define("FILENAME_EDIT", "editfeedback.php");
define("FILENAME_DELETE", "deletefeedback.php");
include this php file in every other file where you want to access the filenames (generally in every file that you create).
Is this approach effecient enough ?
The project that I am working on is not fully developed in oops but It uses some of the classes like paginator and session which use oops concepts very well.
Please help me.
Thanks
I’m not sure this really helps, as why would you want to rename a file and yet not rename the constant with the same name? You should just adopt a naming scheme and stick with it.
Like said elsewhere, any decent IDE will automatically update paths and it is better to stick to a naming convention, like PEAR and use autoloading if possible.
The main drawback when using the define approach is, you are littering constants all over the place and risk name clashing with constants defined by vendor libs or even PHP. If you really want to define all your file names in a separate file, put them in an array, e.g.
<?php // config.inc.php
return array(
'addFeedback' => '/file/to/add-feedback.php',
// ...
);
<?php // MyApp.php
$config = require_once 'config.inc.php';
Your config might also reside in an XML, YAML or INI file, but then you'd have to have some sort of Config class being able to read the file. You see this approach often in the current frameworks (ZF, Symfony).
Apart from that, having the filenames for the actions your app is about to offer to the outside world is a perfect Use-Case for the FrontController pattern and MVC. Combined with the aforementioned naming convention and autoloading, you won't have to bother about including filenames anymore at all.
Any good IDE will do the job for you, if you rename a file, references will be updated.
Well, another option may be to have a "inc.top.php" file that does all your includes.
If you're already including a file with all the constants, why not just do all the file includes in that file instead and include that at the top of each file?
I would advise sticking to a naming convention from the get-go because it'll reduce the possibility of producing "cheese puff moments" where you spend hours trying to track down a bug that turns about to be "oh...I forgot to rename my file!"
Why not choose a naming convention and then just use an autoloader to handle all the resolution? Or even some standardized include process. Thousands of PHP applications do it - including WordPress and Drupal with 1000's of developers - with minimal effort combined with strict conventions.
Good design dictates only writing each function once. In PHP I'm doing this by using include files (like Utils.php and Authenticate.php), with the PHP command include_once. However I haven't been able to find any standards or best practices for PHP include files. What would you at StackOverflow suggest?
I'm looking for:
Naming Standards
Code Standards
Design Patterns
Suggestions for defining return types of common functions
(now I'm just using associative arrays).
One convention I like to use is to put each class in its own file named ClassName.class.php and then set up the autoloader to include the class files. Or sometimes I'll put them all in a classes/ subdirectory and just name them ClassName.php. Depends on how many class vs. non-class includes I'm expecting.
If you organize your utility functions into classes and make them static methods instead, you can get away with writing only a single require_once() in your top level files. This approach may or may not be appropriate for your code or coding style.
As for return types, I try to follow the conventions used in the built-in functions. Return a type appropriate to the request, or return false on failure. Just make sure you use the === operator when checking for false in the results.
The fact that you're concerned about conventions suggests you're already on the right track. If you are familiar with any other OOP language like Java, C++, C#, etc., then you'll find you can follow a lot of the same conventions thanks to the OOP goodness in PHP5.
Whatever naming convention you end up using (I prefer to take cues from either Java or C# wherever possible) make sure if you use include files for functions that they do not actually execute any code upon including, and never include the same file twice. (use include-once or require-once)
Some such standards have been written already. Most large projects will follow and standard of their own.
Here is one written by Zend and is the standard used in the Zend framework.
http://framework.zend.com/manual/en/coding-standard.html
Also, PEAR always had some fairly strict coding standards:
http://pear.php.net/manual/en/standards.php
My preferred answer though is that for your own project you should use what you feel comfortable with, and be internally consistent. For other projects, follow their rules. The consistency allows for greatest code readability. My own standards are not the same as the PEAR ones. I do not indent with four spaces (I use tabs) and I never use camel case like function names, but nonetheless if I am editing something from another project I'll go with whatever that project does.
I've done the following. First, I created an intercepting filter, to intercept all web requests, I also created a version which would work with command line commands.
Both interceptors would go to a boot strap file, which would setup an autoloader. This file as the autoloading function and a hash. For the hash the key is the class name, and the value is the file path to the class file. The autoload function will simply take the class name and run a require on the file.
A few performance tips if you need them, use single quotes in defining the file, as they're slightly faster since they're not interpreted, also use require/include, instead of their _once versions, this is guaranteed to run once, and the former is a fair bit faster.
The above is great, in fact, even with a large code base with a tonne of classes, the hash isn't that big and performance has never been a concern. And more importantly we're not married to some crazy pseudo name space class naming convention, see below.
The other option is delimited name, pseudo name space trick. This is less attractive as name spaces will come with 5.3 and I see this being gross as renaming these across the code base will be less fun. Regardless, this is how it works, assume a root for all your code. Then All classes are named based on the directory traversal required to get there, delimited by a character, such as '_', and then the class name itself, the file will be named after the class, however. This way the location of the class is encoding in the name, and the auto loader can use that. The problem with this method besides really_long_crazy_class_names_MyClass, is that there is a fair bit of processing on each call, but that might be premature optimisation, and again name spaces are coming.
eg.
/code root
ClassA ClassA.php
/subfolder
subFolder_ClassB ClassB.php