I'm trying to familiarize myself with the Craft architecture and I can't understand whether I should be extending craft\base\Component
or craft\base\Model
for my business logic models. Component seems like a pretty lean class that only adds a few initialization events to Model.
1 Answer
Models are classes that contains abstractions of the reality, for example you could have the model car that contains the technical information about it, how many wheels it has and it's brand. Models are usually not supposed to contain any logic. So it's just a "container" with information
Components are more like services that contains business logic to work with your models, for example the service car would handle the logic to let your car model drive and move and such. Components in Yii2 are mostly (not always) treated as singletons while you want to have many different instances of your models
-
Thanks for the clarification! I just realized Services in Craft were actually extending Components in Yii. A bit confusing in terminology, but I'm starting to wrap my head around it!– LazloAug 28, 2018 at 19:51
-
A minor caveat, and a caution. First the caveat: there is a strong argument that anemic models are an anti-pattern. That said, Robin is correct in stating that this is The Craft Way™. That leads me to the caution: bear in mind that your service classes "define your plugin’s API, which your plugin (and other plugins) can access" (source; emphasis added). Aug 29, 2018 at 6:06