Creating a Utility class in Yii2

A Utility class is a place to put all common methods that will often need to be re-used in a web software application. During a previous article it was demonstrated how to create a master Model and Controller …

Create a master Model and Controller in Yii2

The master Model and Controller are good places to store a lot of re-used methods that relate to Models and Controllers. Sometimes though methods may not relate to Models and Controllers and need to re-used elsewhere in the web software application. This is where the Utility is useful. It is important to note that the Utility class is not designed to be instantiated as an object and should contain “static” methods that can act independently.

To create a Utility class create a new file called “Utility.php” and place it inside your “components” folder. Inside the “Utility.php” file place the following code …

The above code shows a blank Utility class ready to be populated with re-usable methods. Below shows a Utility class with an example method …

Notice how the method is defined as “static”, this is because the Utility class will not be instantiated into an object when used in the web software application. The method within the Utlity class can be used in the web software application as follows …

Include the Utility class into the file the Utility class will be used in …

Now call the desired Utility class method …

I personally create a Utility class in all my web software applications and find it a useful place to store re-usable methods that do not relate to Models and Controllers. Re-usable methods that do relate to Models and Controllers I store in the master Model and Controller, re-usable methods that do not relate to Models and Controllers I store in the Utility class.

2130 Total Views 12 Views Today

One thought on “Creating a Utility class in Yii2”

Leave a Reply

Your email address will not be published. Required fields are marked *