Skip to content

Tutorial Create Module

M ABD AZIZ ALFIAN edited this page Aug 14, 2018 · 13 revisions

Create new App or Module

In this tutorial, we will create very simple app or module.

Requirement structure

For every basic structure module is require:

  1. package.json
  2. MainClass.php >> Assume this is your main class
  3. mainclass.router.php >> Assume this is router for your main class
  4. index.php
  5. README.md
  6. LICENSE.md

Begin to create module first_mod

Now we start to create first module name FirstMod
Directory/folder name is first_mod
And namespace will be modules/first_mod because namespace should following the parent directory/folder name

1. Create file package.json

Here is the minimum structure of package.json

{
    "package": {
        "name": "FirstMod",
        "url": "https://github.com/aalfiann/reslim-modules-first_mod",
        "description": "This is my first reslim modules",
        "version": "1.1",
        "require": {
            "reSlim": "1.9.0"
        },
        "license": {
            "type": "MIT",
            "url": "https://github.com/aalfiann/reslim-modules-first_mod/blob/master/LICENSE.md"
        },
        "author": {
            "name": "M ABD AZIZ ALFIAN",
            "url": "https://github.com/aalfiann"
        }
    }
}

Explanation:

  • package->name : This is your project name
  • package->url : This is your project url
  • package->description : This is your project description
  • package->version : This is your project version
  • package->require : This to set what is the minimum reslim version for your project requirement
  • package->license->type : This is the type of the license. Ex. MIT, Apache2, etc.
  • package->license->url : This is the url of the license.
  • package->author->name : This is the name of the author project
  • package->author->url : This is the url to contact the author

Note:
If your project require other module, just add this in package.json

"dependency": [
    "modules/othermodule1",
    "modules/othermodule2",
    "modules/othermodule3"
]

2. Create class file FirstMod.php

This is your main class FirstMod

<?php
namespace modules\first_mod;                        //Make sure namespace is same structure with parent directory
use \classes\Auth as Auth;                          //For authentication internal user
use \classes\JSON as JSON;                          //For handling JSON in better way
use \classes\CustomHandlers as CustomHandlers;      //To get default response message
use PDO;                                            //To connect with database
	/**
     * This is my First Modules class
     *
     * @package    modules/first_mod
     * @author     M ABD AZIZ ALFIAN <github.com/aalfiann>
     * @copyright  Copyright (c) 2018 M ABD AZIZ ALFIAN
     * @license    https://github.com/aalfiann/reSlim-modules-first_mod/blob/master/LICENSE.md  MIT License
     */
    class FirstMod {
        //database var
        protected $db;
        //base var
        protected $basepath,$baseurl,$basemod;
        //master var
	var $username,$token;
        
        //construct database object
        function __construct($db=null) {
            if (!empty($db)) $this->db = $db;
            $this->baseurl = (($this->isHttps())?'https://':'http://').$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
            $this->basepath = $_SERVER['DOCUMENT_ROOT'].dirname($_SERVER['PHP_SELF']);
            $this->basemod = dirname(__FILE__);
        }
        //Detect scheme host
        function isHttps() {
            $whitelist = array(
                '127.0.0.1',
                '::1'
            );
            
            if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){
                if (!empty($_SERVER['HTTP_CF_VISITOR'])){
                    return isset($_SERVER['HTTPS']) ||
                    ($visitor = json_decode($_SERVER['HTTP_CF_VISITOR'])) &&
                    $visitor->scheme == 'https';
                } else {
                    return isset($_SERVER['HTTPS']);
                }
            } else {
                return 0;
            }            
        }
        //Get modules information (no database required)
        public function viewInfo(){
            return file_get_contents($this->basemod.'/package.json');
        }
        //Determine token validation (required database)
        public function checkToken(){
            if (Auth::validToken($this->db,$this->token,$this->username)){
                $data = [
                    'status' => 'success',
                    'code' => 'RS304',
                    'message' => CustomHandlers::getreSlimMessage('RS304')
                ];
            } else {
                $data = [
	    	    'status' => 'error',
		    'code' => 'RS401',
        	    'message' => CustomHandlers::getreSlimMessage('RS401')
		];
            }
            return JSON::safeEncode($data,true);
	    $this->db= null;
        }
    }

3. Create router file firstmod.router.php

It is very important that the names of the router files to follow this pattern: name.router.php

<?php
//Define interface class for router
use \Psr\Http\Message\ServerRequestInterface as Request;        //PSR7 ServerRequestInterface   >> Each router file must contains this
use \Psr\Http\Message\ResponseInterface as Response;            //PSR7 ResponseInterface        >> Each router file must contains this
//Define your modules class
use \modules\first_mod\FirstMod as FirstMod;                    //Your main modules class
//Define additional class for any purpose
use \classes\middleware\ApiKey as ApiKey;                       //ApiKey Middleware             >> To authorize request by using ApiKey generated by reSlim
    // Get module information
    $app->map(['GET','OPTIONS'],'/first_mod/get/info/', function (Request $request, Response $response) {
        $fm = new FirstMod($this->db);
        $body = $response->getBody();
        $response = $this->cache->withEtag($response, $this->etag2hour.'-'.trim($_SERVER['REQUEST_URI'],'/'));
        $body->write($fm->viewInfo());
        return classes\Cors::modify($response,$body,200,$request);
    })->add(new ApiKey);
    
    // Token Validation 
    $app->get('/first_mod/check/token/{username}/{token}', function (Request $request, Response $response) {
        $fm = new FirstMod($this->db);
        $fm->username = $request->getAttribute('username');
        $fm->token = $request->getAttribute('token');
        $body = $response->getBody();
        $body->write($fm->checkToken());
        return classes\Cors::modify($response,$body,200);
    });

4. Create index file index.php

This index.php just to prevent user directly route to your url project module

<?php header('Content-type:application/json; charset=utf-8');header("Access-Control-Allow-Origin: *");header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Origin, Authorization");header('HTTP/1.0 403 Forbidden');echo '{
  "status": "error",
  "code": "403",
  "message": "This page is forbidden."
}';?>

5. Create file README.md

Remember that the letters of README must uppercase

### Detail module information

1. Namespace >> **modules/first_mod**
2. Zip Archive source >> 
    https://github.com/aalfiann/reSlim-modules-first_mod/archive/master.zip

### How to Integrate this module into reSlim?

1. Download zip then upload to reSlim server to the **modules/**
2. Extract zip then you will get new folder like **reSlim-modules-first_mod-master**
3. Rename foldername **reSlim-modules-first_mod-master** to **first_mod**
4. Done

### How to Integrate this module into reSlim with Packager?

1. Make AJAX GET request to >>
    http://**{yourdomain.com}**/api/packager/install/zip/safely/**{yourusername}**/**{yourtoken}**/?lang=en&source=**{zip archive source}**&namespace=**{modul namespace}**

### Want to learn other modules?

We have several modules for you to learn.  
Just visit >> [reSlim modules](https://github.com/aalfiann/reslim-modules)

6. Create file LICENSE.md

Remember that the letters of LICENSE must uppercase

Copyright (c) 2018 M ABD AZIZ ALFIAN

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Manual Integration into reSlim

  1. Go to folder src/modules
  2. Create directory/folder name first_mod
  3. Paste all this files into directory first_mod
  4. Done

Auto integration into reSlim with Packager module

Requirements

To create online installation with Packager module is require:

  • Zip Archive source must be online

A. Create Zip Archive Source

  1. Create repository in github for example is reslim-modules-first_mod
  2. Upload all this files to your github repository,
    then you will get the archive source is >> https://{github.com/youraccount}/reslim-modules-first_mod/archive/master.zip
  3. Namespace is modules/first_mod

B. Installation with Packager module

Make AJAX GET request to >> http://{yourdomain.com}/api/packager/install/zip/safely/{yourusername}/{yourtoken}/?lang=en&source={zip archive source}&namespace={modul namespace}


Thanks for using reSlim
All of this source module is available in here >> https://github.com/aalfiann/reSlim-modules-first_mod

Start with Starter package

You can save more minutes to create an app quickly with just modify this >> Starter

Want to learn other modules?

We have several modules for you to learn.
Just visit >> reSlim modules