Mix of PHP functions and classes in one file? - php

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.

Related

PHP - get all declared resources (traits, classes, functions and constants) within a given script?

I designed a PHP 5.5+ framework comprised of more than 750 different classes to make both web applications and websites.
I would like to, ideally, be able to reduce its size by producing a version of itself containing just the bare essential files and resources needed for a given project (whether it's a website or a web application).
What I want to do is to be able to:
reduce the amount of traits, classes, constants and functions to the bare essential per project
compress the code files to achieve a lesser deployment size and faster execution (if possible)
So far, I've got the second part completed. But the most important part is the first, and that's where I'm having problems. I have a function making use of get_declared_classes() and get_declared_traits(), get_defined_constants() and get_defined_functions() to get the full list of user-defined classes, traits, functions and constants. But it gives me pretty much EVERYTHING and that's not what I want.
Is there a way to get all defined classes, functions and constants (no need for traits as I could run class_uses() on every class and get the list of traits in use by that class) for a single given script?
I know there's the token_get_all() function but I tried it with no luck (or maybe it's I'm using it the wrong way).
Any hint? Any help would be greatly appreciated :)
You can use PHP Parser for this. It constructs abstract syntax trees based on the files you supply to it. Then you can analyze its output for each file, and produce a report usable to you.
Other than that, you can use token_get_all() approach you've mentioned already, and write a small parser yourself. Depending on your project, this might be easier or more difficult. For example, do you use a lot of new X() constructs, or do you tend to pass dependencies via constructors?
Unfortunately, these are about the only viable choices you have, since PHP is dynamically typed language.
If you use dependency injection, however, you might want to take a look at your DI framework's internal cache files, which often contain such dependency maps. If you don't use such framework, I recommend to start doing this, especially since your project is big and that's where dependency injection excels at. PHP-DI, one of such frameworks, proved to be successful in some of my middle-size projects (25k SLOC).
Who knows? Maybe refactoring your project to use DI will let you accomplish the task you want without even getting to know all the dependencies. One thing I'm sure of is that it will help you maintain it.

Organising classes - Best practice?

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

What should be the standard PHP code file lenth in LOC?

I do PHP coding a lot in my company and personal work. Usually my files get bigger, sometimes more than 2000-3000 lines long. Then, they get difficult to manage.
My Question: What should be (is) the standard length of a PHP code file in terms of lines-of-code. At what length do you guys split it up?
Note: No Object Oriented programming (I don't use classes). Please answer accordingly.
Clarification of not using classes:
I do use functions a lot.
I don't use classes because the code is legacy. I have to maintain that and add new features.
I was a C programmer before. So, going OO is somewhat tough for me. Like learning whole new way of doing things.
There is no good standard length. Some files grow bigger, some smaller.
A good guiding principle from Object Oriented Programming is separating tasks and concerns into classes, and splitting those classes into separate files.
That is the most logical separation, and allows using PHP 5's Autoloading. The basic principles may be worth adopting even if you don't want to get into serious OOP.
Related questions:
What are the advantages/disadvantages of monolithic PHP coding versus small specialized php scripts?
Code should not be split according to number of lines of code, it should be split according to functionality. Parts of your code that handle, say, templating, should go in different files (and possibly directories) than parts that handle, say, authentication. If you have a file that's thousands of lines long, it's almost certainly doing way too much and needs to be split up, if not refactored entirely.
Maybe you should start using classes then.
BTW, I definitely split the PHP code files at 1000 lines of code.
Use classes and OO programming. I have been to an workshop once "make love to your code" that stated to avoid functions that are longer as the space on your monitor (you should not scroll to look at the whole function)
Even quite large code files can be reasonably easy to manage if you organise them well. You should keep your functions short, keep related functions together, and name them well.
You will also find it easier to manage if you use an IDE with a function lookup table - I use Netbeans, and on the left hand side it gives me a panel with quick links to all the functions in my current file. It also gives me the ability to click on a line where a function is called and jump to the declaration (anwhere in the project).
On the other hand, if you have code files several thousand lines long which consist of a single function, then yes, the odds are it will be very hard to manage, an no amount of IDE cleverness will help.

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.

Is there such a thing as an over use of PHP's include()?

I am using includes to pull in the various functions I am using, and I am now starting to use include to pull in chunks of HTML/PHP. Is there a point where I have overused includes?
As soon as you start having problems reading your own code that you wrote some time ago, it's definitely too much.
I recommend programming in object oriented PHP and using autoloaders to avoid include/require as far as possible. Excessive use of include/require often leads to unreadable and unmaintainable spaghetti code, which is very bad.
In small projects I usually just have one require statement to pull in my autoloader function(s) and in larger applications I use Zend Framework where I rely on Zend_Loader exclusively.
From a purist point of view I'd say: More than 3 includes/requires in your own code (without third party libs) is too much:
One for inluding some iniitialization stuff
One for loading the autoloader class/function
And the one in the autoloader itself. There should only be one function that actually incudes/requires files. That function or method can then be reused in extended autoloader classes.
I mostly try to stick to that principle.
I'd say it depends to what point your code is still readable. If someone not working on your project have difficulties to understand your code then yes, includes are overused.
You can overuse anything but it's probably not doing you that much harm (just a few extra stats here and there). You have to remember that large projects like Drupal and Wordpress do hundreds, if not thousands of includes.
If you're hooking in HTML, you might be getting a bit desperate. I'd personally have a good look at a proper templating language or even a framework that helped you into a MVC or MVT stance. It makes maintaining it a lot easier than chasing includes all over the place and (more importantly), keeps 95% of your logic out of your presentation files. Oh and they can maintain your databases in a much more programmatic modular method.
Basically Frameworks give you a lot of development benefits ;)
Symphony and CakePHP are both good frameworks but if you just want a look at templating, have a go with Smarty.
If all you are using is includes then I would look into another way of doing it.
For example if you have a separate file for every function maybe look into putting them all in one file or putting them with similar functions.
It's really a matter of architecture and optimisation. Rather than discuss what's the optimal number of includes per script, I'd advise using a template engine, e.g. Smarty because it allows you to:
Separate markup from the program logic
Use template tags and built-in functions to considerably ease the development
Cache preprocessed PHP files making the whole thing a lot faster for your users

Categories