ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
### **It's All About The Layers** ### As you may have noticed, a key to solid application design is simply separating responsibilities, or creating layers of responsibility. Controllers are responsible for receiving an HTTP request and calling the proper business layer classes. Your business / domain layer is your application. It contains the classes that retrieve data, validate data, process payments, send e-mail, and any other function of your application. In fact, your domain layer doesn't need to know about "the web" at all! The web is simply a transport mechanism to access your application, and knowledge of the web and HTTP need not go beyond the routing and controller layers. Good architecture can be challenging, but will yield large profits of sustainable, clear code. For example, instead of accessing the web request instance in a class, you could simply pass the web input from the controller. This simple change alone decouples your class from "the web", and the class can easily be tested without worrying about mocking a web request: ~~~ <!-- lang:php --> class BillingController extends BaseController{ public function __construct(BillerInterface $biller) { $this->biller = $biller; } public function postCharge() { $this->biller->chargeAccount(Auth::user(), Input::get('amount')); return View::make('charge.success'); } } ~~~ Our ``chargeAccount`` method is now much easier to test, since we no longer have to use the Request or Input class inside of our ``BillingInterface`` implementation as we are simply passing the charged amount into the method as an integer. Separation of responsibilities is one of the keys to writing maintainable applications. Always be asking if a given class knows more than it should. You should frequently ask yourself: "Should this class care about X?" If answer is "no", extract the logic into another class that can be injected as a dependency. > Single Reason To Change A helpful method of determining whether a class has too many responsibilities is to examine your reason for changing code within that class. For example, should we need to change code within a ``Biller`` implementation when tweaking our notification logic? Of course not. The ``Biller`` implementations are concerned with billing, and should only work with notification logic via a contract. Maintaining this mindset as you are working on your code will help you quickly identify areas of an application that can be improved. >