Yii: Following strict MVC rules to ensure that all the business logic is in appropriate places

StackOverflow https://stackoverflow.com/questions/13177824

  •  25-07-2021
  •  | 
  •  

Question

Sticking to MVC basics in Yii, I am trying to embed my business rules in the model class but facing problem in implementing it. The problem at hand is to stop the user from making duplicate entries and code the function in model class that checks if the entry already exists in table. I want to write a method in my model class which would query the sames model's underlying table and if the new business entity exists, it simply returns false. If I code this in controller, I can achieve the desired functionality but I want to keep this in model so that where ever the model is used, I can access the method and also stick to MVC basics which dictates Thin Controllers and Thick Models. Thanks in advance.

Was it helpful?

Solution

Cross-site Request Forgery Prevention may be what you are looking for? unless your idea of 'duplicate entries' is directly related to your business model, in which case you can override the CActiveRecord.beforeSave() and put your logic in there, if this method returns false, the record won't be saved to the database.

If you use the later method, and you want to pass the error to the view and display to the user, you can always use the CModel.addError() method, in this case in your beforeSave method.

There is another option though, which is using custom validators.

which is more appropriate? depends on your business logic.

OTHER TIPS

The best way would be to avoid the use of active record instances (at least) directly in the controller.

Instead you should create service-like structures, which contains the interaction between your CActiveRecord and CFormModel instances. This would let you better isolate the presentation layer (views, controllers and templates) from model layer.

Such services also would be able to hold (and sometimes, react upon) errors/exceptions thrown by CActiveRecord and CFormModel instances, that it utilizes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top