PHP file naming conventions (.class, .inc) - php

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.

Related

Should PHP scripts have multiple classes in the same file?

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';
}

PHP (A few questions) OO, refactoring, eclipse

I am using PHP in eclipse. It works ok, I can connect to my remote site, there is colour coding of code elements and some code hints.
I realise this may be too long to answer all questions, if you have a good answer for one part, answering just that is ok.
Firstly General Coding
I have found that it is easy to
loose track of included files and
their variables. For example if
there was a database $cursor it is
difficult to remember or even know
that it was declared in the included
file (this becomes much worse the
more files you include). How are
people dealing with this?
How are people documenting their
code - in particular the required
GET and POST data?
Secondly OO Development:
Should I be going full OO in my
development. Currently I have a
functions library which I can
include and have separated each
"task" into a separate file. It is a
bit nasty but it works.
If I go OO how do I structure the
directories in PHP, java uses
packages - what about php?
How should I name my files, should I
use all lower case with _ for spaces
"hello_world.php"? Should I name
classes with Uppercase like Java
"HelloWorld.php"? Is there a
different naming convention for
Classes and regular function files?
Thirdly Refactoring
I must say this is a real pain. If
I change the name of a variable in
one place I have to go through whole
document and each file that included
this file and change the name their
too. Of course, errors everywhere
is what results. How are people
dealing with this problem? In Java
if you change the name in one place
it changes everywhere.
Are there any plugins to improve php
refactoring? I am using the
official PHP version of Eclipse from
their website.
thanks
Firstly General Coding
1) OO can help you with that. As you encapsulate variables and functionality, they don't go out and mess with the namespaces. Assumind I understand right what problem you hint at, using an OO approach helps alleviating conflicts that can arise when you are inadvertedly redeclaring varables. (Note: Alleviate. Not completely prevent on its own. ;))
Otherwise a practise i have encounterd is prepending variable names with something like a 'package name' -- which merely shifts the problem one level up and isn't exactely beautiful either. :|
2) "However suits their purpose". PHPdoc is a good start; will help to create API documentation.
Secondly OO Development:
3) As said before -- "it depends". Do it when needed. You don't have to go full OO for "hello world". But you can. Weigh the costs and benefits of either route and choose wisely. Though I personally want to suggest when in doubt favour OOP over 'unstructured' approaches. Basically, know your tools and when to use them -- then you can make that call on your own easily. :)
4) As far as I can see, the directories "are structured like packages". Mind you, "directories" and "like". Having said that, various frameworks have solved that problem for theirselves; cf; th eother answers.
5) Again, however you please. There is not a definitive way You Have To Do It Or Else. Just stick to it once you chose your path ;3
Aside of that certain frameworks etc. have their own naming conventions. Symfony, e.g., uses CamelCase like Java.
Thirdly Refactoring
I must say this is a real pain.
yes :3 But it pays off.
If I change the name of a variable in one place I have to go through whole
document and each file that included this file and change the name their too.
Of course, errors everywhere is what results. How are people dealing with
this problem? In Java if you change the name in one place it changes everywhere.
No, it doesn't. If you get yourself a tool with support you only have to use the refactoring tool once; but if you rename a class property in java, there is no magic bot that walks through the internet and automagically makes sure everyone on the planet uses the new name. ;)
But as for how to prevent it -- be smart. Honour program contracts, i.e. use interfaces. Do not use functions / members you shouldn't use directly. Watch the hierarchies. Use a reasonable division of code and respect this division's boundaries.
But how people deal with that problem? Well, search and replace I suppose ;)
As for the Eclipse-Plugin -- The dynamic nature of PHP makes it more difficult to automagically refactor code; we can't always use static type hinting etc., and divination of argument and return types is impossible more often than not. So, to the extent of my knowledge, 'automatic refactoring' is not as well-supported by tools as in the Java world. Though I am sure for the doable cases, there should be plugins. :)
I've found using a PHP framework (e.g. Zend, Cake, CodeIgniter, etc) can force class structures and naming conventions while generally addressing autoloading as well. Using PHPDoc formatting liberally helps with code-completion and hinting as well as documenting specific requirements (e.g. method parameter definitions).
For the OO Development part:
I am using the autoload functionality to load the classes dynamically. My directory structure is like packages in java. My classes are named like in java (e.g. HelloWorld.php). But the class is defined with the complete path to that class (e.g. class FW_package1_package2_HelloWorld {...}).
If a class is called the autoload method replaces all _ against / and searches for the class with the extracted path (e.g. FW/package1/package2/HelloWorld.php).
I am strongly influenced by Java, so that I chose this way.
Take a look at nWire for PHP. It is a plugin for Eclipse PDT which provides code exploration and visualization.
It can easily be used to trace dependencies within your application and it is very handy for OO projects, enabling you to visualize class hierarchies and much more.
It doesn't support refactoring, but it can assist by showing you the references of a given components (e.g. a function or a field).

how do I manage filenames in my php project

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.

PHP include file extension best practices

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.

Design Tips for PHP Function Include Files

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

Categories