First off, I'll admit that I'm anal about such things. (Bad, bad, me.) However, I'm just wondering what's considered best practice in terms of naming PHP include files.
As a base case I'm going to keep .php as the final extension (to help prevent un-parsed files being fetched), but to aid distinguishing between a front end file and an include file I'm either going to:
Name all of the include files XXX.inc.php
Name generic (non class) files as above and class definitions as ClassName.class.php (Potentially handy for auto-loader utilisation down the line, although I'm not a big fan of auto loaders.)
I'm currently plumping for option 2, but I'm just wondering if there are any other suggestions or bits of advice you'd recommend.
First of all, I totally agree with you when you say that all PHP files should have ".php" as a final extension ; two reasons for that :
as you stated, it helps prevent un-parsed files being fetched
it also helps with IDE/editors that do syntax-coloration based on filename : you don't have to configure it to consider ".inc" as a PHP file.
There are cases when I do otherwise, though ; the main reason for that is when I'm using a tool (CMS, Framerwork, library, ...) that has some rules about naming of files : I tend to follow those, even if I don't like them.
For instance :
With Drupal, I use ".inc", ".module", ".install", ...
With Zend Framework, I use ".phtml" for views scripts (HTML+PHP)
For files that contain classes, I don't like ".class.php" : I think it's kinda redundant ; I tend to use "MyClassName.php", and use this for autoload.
(BTW, that's what Frameworks like Zend Framework or Doctrine ORM recommend)
As a sidenote : you say you are not a big fan of autoloaders ; why ?
I use those as much as I can :
generally better for performance : only the code you really use is loaded / parsed
less code to write (no require/include)
I use ClassName.class.php for class files and SomeDescription.lib.php for non-class files.
Not a fan of .inc.php. Seems somehow wrong to describe the file in terms of how it may possibly be imported, instead of its content.
Related
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 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.
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.
I see .class and .inc included in file names a lot of the time. My current understanding is that this is just a best practice to make the purpose/contents of the file clear.
Is there any instance in PHP where a .class or .inc file name has a special purpose and truly means something?
As far as the PHP interpreter is concerned there's no behavioural reason to include these descriptors at all. The de facto convention seem to be, to include them as part of the file suffix however I find it more useful to prefix them - i.e. my file names tend to look like:
class.*.php
inc.*.php
tpl.*.php
This is purely for organisational purposes; Whenever an application / terminal lists them in alphanumerical order each "type" will be grouped together. To conclude the question though it's really just down to preference, the only thing that's important - whatever you choose - is consistency.
Not really
Depending on how you have your .htaccess file set up, it can determine which classes are visible to the world. I believe best practice still says to end every file with .php if you can.
I make my class files end with .class.php so I can see it's a class but no-one can view the source.
It is suggested by PHP best practice coding standards to name classes with class keyword somewhere in the class file name. However, the final decision is yours whether you want to stick with that or not. It has nothing to do with code execution.
In my opinion the best practice is to use a Framework and use the same naming conventions they uses in their sample projects. I don't think there is a Standard for it since it doesn't make a difference.
Most people name their classes as *.class.php and their static files as *.inc.php.
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