Skip to content

Core\Service

Fariz Luqman edited this page Jan 22, 2017 · 4 revisions

In the MVC framework, the Service layer acts as the most sophisticated way to "use" methods or applications. The Service layer will act as a bridge of the final interface/layer like the View or APIs you are writing with any other complex methods like performing database queries (Model), or performing updates to the database (Controller) etc.

If you are writing your own applications, you can make use of the Service layer.

Configuring Services

All services are defined in the file /config/services.php

/*
|--------------------------------------------------------------------------
| Services
|--------------------------------------------------------------------------
|
| All of your applications will be mapped here, and can be accessible
| with the $service object in your app.
| 
| e.g: $service->test->hello();
|
| 'the class name' => 'the variable name for accessing your written applications'
|
*/

return [
    'Service\Test\TestService' => 'test'
];

Writing Services / Applications

All services will be in the directory /app/Service. An example of service:

<?php
namespace Service\Test;

class TestService extends \Core\Service
{
    public function hello()
    {
        return 'Hello';
    }
    
    public function calculate(int $var1, $operation, int $var2)
    {
        if($operation == 'plus' || $operation == '+')
        {
            return $var1 + $var2;
        }else if($operation == 'minus' || $operation == '-')
        {
            return $var1 - $var2;
        }else if($operation == 'multiply' || $operation == '*')
        {
            return $var1 * $var2;
        }else if($operation == 'divide' || $operation == '/')
        {
            return $var1 / $var2;
        }else{
            return 'Invalid Operation';
        }
    }
    
    public function getRegisteredUsers()
    {
        return \Model\User::all();
    }
}

Accessing Services

Services that are written can be accessed anywhere in the View files like this:

$service->test->hello();

or

<html>
<body>
     <p>2+1 is = <?= $service->test->calculate(2,'+',1); // outputs 3 ?></p>
</body>
</html>

Visit our website for tutorials: stupidlysimple.github.io

Clone this wiki locally