I am designing a new application and plan to use CakePHP 3. Typically when designing an application on top of a PHP MVC framework (CakePHP, CodeIgniter) I have implemented a separate set of classes that represents the business layer or service layer (depending on what words you like to use). Thus, the stack:
-- Views
-- Controllers [really just another part of the views; code-behind from C# land]
-- Business layer [where business logic goes, because business logic spans multiple domain objects and isn't appropriate for a single Model/DAO]
-- Models [aka Data Access Objects]
...with domain objects (now "Entities" in Cake PHP 3) traversing between the layers.
I see that Cake PHP 3 still lacks any concept of a business layer in the default architecture, which is disappointing but hardly insurmountable. But after all that, my question is actually rather pedestrian. It is: Where do I put MyBusinessLayer.php? In Cake PHP 2 I would have put it in app/Lib, and loaded it up with
App::Import('Lib', 'MyBusinessLayer');
What is the equivalent in CakePHP 3, and how do I load it? I realize I could just stick it any old place and require_once(), but I wonder if there is a way that is more consistent with Cake PHP standards. This question could just as easily apply to a ten-line utility class, but in my case it applies to the business layer.
Your business layer can be put anywhere under the src
directory. For example you could have a folder called src/Core
or src/MyBusiness
or you could have multiple folders like src/Command
src/Handler
, it is up to you how you want to architecture your application other than serving a web request or accessing data in the database.
Classes put inside any folder inside src
will be automatically loaded if given the right namespace.
// in src/MyBusiness/BusinessRules.php
namespace App\MyBusiness;
class BusinessRules
{
...
}
You can automatically load this class from another use the use
keyword:
// In another file
use App\MyBusiness\BusinessRules;
...
$rules = new BusinessRules();
CakePHP does not make assumptions for you when it comes to this kind of objects as they usually are very specific to your application. It does offer a wide variety of tools that can help you build a better architecture more rapidly and with less code. For example using the Event
system for Aspect Oriented Programming, the configuration traits for creating adaptable implementations or the Collection
library for working with data using a functional approach.
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