I have a doubt about the right way/best practice about loading dependent classes in PHP.
I usually put all dependencies in the beginning of each class with a include_once
in a way similar to Java imports. Something like:
include_once 'dto/SomeObjectDTO.php;'
include_once 'dao/SomeObjectDAO.php;'
include_once 'util/SomeObjectUtil.php;'
class SomeObjectService{
#class code here
}
This is the best way to load classes? Or maybe load all classes in a Bootstrap.php
? Other ways?
Note that I'm talking about loading my own classes, not complex external classes like frameworks.
Dependencies are PHP libraries, frameworks, and components that you can use in your web development projects. They help to make coding easier and more efficient, and most projects will rely on a number of them. The issue with dependencies lies in how difficult they can be to manage.
Using a dependency manager provides instant access to your packages, frameworks, and other components during a project, as and when you need them. As a result, you can save yourself the headache of having to download them each time. Fortunately, it’s easy to install and get started with Composer in just four steps:
Composer keeps track of your project’s dependencies in a file called composer.json. You can manage it by hand if you like, or use Composer itself. The composer require command adds a project dependency and if you don’t have a composer.json file, one will be created. Here’s an example that adds Twig as a dependency of your project.
Like Homer6 said, autoloading is a php's built in dependency loading mechanism. PHP-FIG proposed a family of PHP coding standards called PSR. PSR-0 deals with class naming and autoloading. Here are some links: Also, keep in mind, that autoloading comes with a price.
Like Homer6 said, autoloading is a php's built in dependency loading mechanism.
PHP-FIG proposed a family of PHP coding standards called PSR. PSR-0 deals with class naming and autoloading. Here are some links:
Also, keep in mind, that autoloading comes with a price. There is a lot of string work and work with the fs in the proposed default autoloader(you can implement your own faster autoloader, but it is not going to conform to the standard). This makes autoloading slow when you need to load a lot of classes. So if you needed to load 2 classes only, your approach would be faster and more understandable.
Since version 5.3 PHP supports namespaces. This allows you to have a package and class hierarchy just like you know them from C++ or Java.
Check out those resources to learn more:
http://www.php.net/manual/en/language.namespaces.basics.php
http://php.net/manual/en/language.namespaces.importing.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With