sFire PHP Framework

Helpers

Helpers extends your application with features that can be used in your controller, mappers and even in the view.

In this section we will handle:

  • Creating helpers
  • Using helpers

Creating helpers

Helpers are created in the "modules/{YOUR-MODULE-NAME}/helpers/" folder. By default, the name of a helper begins with "Helper" (you may change this configuration in the app.php.

In this example we are going to create currency/number format helper which will format numbers to currency amounts. This helper will accept two arguments; the number to be formatted and the currency as a string.

<?php
namespace App\Helpers;

class HelperCurrency {

    public function format($number = 0, $currency = '$') {
        return $currency . number_format($number, 2, '.', ',');
    }
}
?>

Note: Our application name is "App". Therefore we use the "App\Helpers" namespace.

Save the helper in "modules/App/helpers/" as "HelperCurrency.php" (mind the case-sensitive name).

Using helpers

Once you created a helper, you may use this extended functionality within your whole application. To use this for example in your controller or mappers, you can call the format function of the helper like:

$this -> helper('Currency') -> format('25', '$'); //Will result in "$25.00"

Now if you want this functionality in your view, you can do this in two ways. The sFire built-in solution or assign the helper as a variable to your view.

Built-in solution

In your view you can call the helper method like this:

@helper('Currency', 'format', 25, '$')

The first parameter is the helper class, while the second parameter is the method you wish to execute. All the other parameters are the arguments your helper method uses.

Assigning

If you don't want to use the built-in helper solution, you can assign the helper from your controller to the view:

Controller:

use App\helpers\HelperCurrency;
use sFire\MVC\ViewModel;

$helper = new HelperCurrency();

$view = new ViewModel('home.index');
$view -> assign('currency', $helper);

View:

{{ $currency -> format(25, '$') }}