Creating components

If you have some code that looks like it can be reused but you don't know if it's a behavior, widget, or something else, most probably it's a component. A component should be inherited from the yii\base\Component class. Later on, the component can be attached to the application and configured using the components section of the configuration file. That's the main advantage compared with using just a plain PHP class. Additionally, we are getting behavior, event, getter, and setter support.

For our example, we'll implement a simple Exchange application component that will be able to get currency rates from the http://fixer.io site, attach it to the application, and use it.

Getting ready

Create a new yii2-app-basic application using ...

Get Yii2 Application Development Cookbook - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.