Mini Framework MVC

      No Comments on Mini Framework MVC

An extremely simple and easy to understand PHP framework suitable to anybody who just wants to show some pages, make some database calls, implement sessions, validate forms, and do some AJAX calls here and there.

Introduction

MINI-FRAMEWORK-MVC is an extremely simple and easy to understand PHP framework based on project MINI3MINI-FRAMEWORK-MVC is NOT a professional framework. As a result, it does not come with all the features and functionalities that real frameworks have. It is limited to a very reduce number of helper libraries.

This project can be suitable to anybody who just wants to show some pages, make some database calls, implement sessions, validate forms, and do some AJAX calls here and there, without the need of reading a lot of documentation of those more advance, complex and professional frameworks. MINI-FRAMEWORK-MVC is easy to install, runs nearly everywhere and doesn’t make things more complicated than necessary.

For a deeper introduction into MINI-FRAMEWORK-MVC root project MINI3, have a look into this blog post: MINI, an extremely simple barebone PHP application.

We really hope this small “framework” can be useful as MINI3 has been to us. If you would like to have a look into our other projects, please visit us at Canchito-Dev.

Features

  • Extremely simple, easy to understand
  • Simple but clean structure
  • Makes “beautiful” clean URLs
  • Integrated with Boostrap v3 and v4.0.0-alpha.6
  • Easy to use database library, which uses PDO for any database requests, comes with an additional PDO debug tool to emulate your SQL statements
  • Easy to use form library for creating and validating form
  • Easy to use e-mail library for sending mails
  • Easy to use session library for hadling sessions
  • Easy to use library for generation pagination
  • Easy to use file upload library
  • Easy to use image manipulation library
  • Demo CRUD actions: Create, Read, Update and Delete database entries easily using the build-in database library
  • Demo form actions: Create and validate form using the build-in form library
  • Demo session actions: handle sessions using the build-in form library
  • Demo mail action: send an e-mail using the build-in e-mail library based on PHPMailer
  • Tries to follow PSR 1/2 coding guidelines
  • Commented code
  • Uses only native PHP code, so people don’t have to learn a framework

History

MINI-FRAMEWORK-MVC started as an idea and a challenge. I am not exactly a professional PHP programmer, but I had the basic knowledge. However, I wanted to improve and learn in dept how a MVC framework was build. So, I bought the book Pro PHP MVC by Chris Pitt, and read it during my free time. In this book, I got the chance to get to know current most popular professional MVC frameworks. And at the same time, the book explains how to build from scratch classes that are useful for a MVC Framework.

To complement the book, I also took the Udemy’s course Learn PHP Model View Controller Pattern (PHP MVC). It was in this course where I understood how to join the different classes need in a framework and got to know MINI3.

After reading the book and finishing the course, I though myself it would be a good idea to combine some of the lessons learnt from both and implement them in MINI3. But I did not want to build everything from scratch. And that is why, some of the libraries are just implementations of already existing ones, whereas some are adaptations of snippets of code, and some others are fully developed by me.

Download & Contribute

Help us find bugs, add new features or simply just feel free to use it. Download MINI-FRAMEWORK-MVC from our GitHub site.

If you would like to become an active contributor to this project please follow these simple steps:

    1. Fork it
    2. Create your feature branch
    3. Commit your changes
    4. Push to the branch
    5. Create new Pull Request

License

The MIT License (MIT)

Copyright (c) 2016, canchito-dev

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.

Dear haters, trolls and everything-sucks-people…

This project started as a way of helping me understand and learn about MVC design pattern. But it grew up to include some other libraries that have been helpful to me. It might not fully follow MVC principles or not perfectly coded, but it was developed with all the good intensions at heart. I also like what our good friend from MINI3 said. So I will just quote him:

“… MINI is just a simple helper-tool I’ve created for my daily work, simply because it was much easier to setup and to handle than real frameworks. For daily agency work, quick prototyping and frontend-driven projects it’s totally okay, does the job and there’s absolutely no reason to discuss why it’s “shit compared to Laravel”, why it does not follow several MVC principles or why there’s no personal unpaid support or no russian translation or similar weird stuff. The trolling against Open-Source-projects (and their authors) has really reached insane dimensions.

I’ve written this unpaid, voluntarily, in my free-time and uploaded it on GitHub to share. It’s totally free, for private and commercial use. If you don’t like it, don’t use it. If you see issues, then please write a ticket (and if you are really cool: I’m very thankful for any commits!). But don’t bash, don’t complain, don’t hate. Only bad people do so….”

The Basics

Requirements

You need a standard Web server with at least:

  • PHP 5.3.2 or higher
  • MySQL
  • Make sure mod_rewrite is enabled and activated
  • Basic knowledge of Composer

For your development environment, I usually use WAMPServer, which is a Windows web development environment, and stands for Windows, Apache, MySQL and PHP.

Now, Composer is a very simple and easy to use dependency manager for PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. You can download the Windows installer from their official site.

Installation

Just follow these steps:

  1. Edit the database credentials in application/config/config.php
  2. Execute the .sql statements in the _install/– folder (with PHPMyAdmin for example).
  3. Make sure you have mod_rewrite activated on your server / in your environment.
  4. Install Composer and run composer install in the project’s folder to download the dependencies and create the autoloading stuff from Composer automatically. For those who are not familiar with Composer, just remember back in the days, when you were using a PHP files with all the includes you needed. Well, Composer creates classes that automatically do this.

MINI-FRAMEWORK-MVC runs without any further configuration. You can also put it inside a sub-folder, it will work without any further configuration.

If you want to test the mail library, you have to modify the configuration under application/config/config.php. At the moment, if you have a Gmail account, you should only need to modify the parameters `SMTP_USERNAME` and `SMTP_PWD` with your own Gmail account and password. If you get errors, you might have to configure your Gmail accout by following this easy step:

Head over to Account Security Settings and enable “Access for less secure apps”, this allows you to use Google’s SMTP for clients other than the official ones.

Security

In order to limit the access to only the /public folder, we use mod_rewrite. These will keep other folder such as the /application folder save from unwanted visitors. To do so, we have created the .htaccessfile. This file alters how Apache web server treats a directory and its contents. To achive this, we have to follow a specific syntax.

Quick Start

The structure in general

After you’ve downloaded and extracted the application, these are the files and folders you should see:

  • _instal: has the SQL files for creating the database demo data
  • application: contains the application you’ re creating. Basically, it holds your models, views, controllers, and other code (like helpers and class extensions). In other words, this is the folder where you do your magic
    • config: holds the configuration file that MINI-FRAMEWORK-MVS uses
    • controller: in this folder you will place your class files developed for your application
    • core: place your base class files of your application
    • libs: place your own developed libraries useful for your application
    • model: data base fetching logic in
    • view: most of your work will be in this folder, you will place your html template files
  • public: public document root of your application. It contains all the files you want to be publically reachable
  • vendor: application dependencies are installed
  • .htaccess
  • composer.json
  • README.md

Whenever there is an URL request, the application will automatically translate the URL-path to the appropiate controllers and their methods inside. Take a look at the following examples:

  • http://localhost/mini-master/home/index will call the index() method in application/controllers/Home.php.
  • http://localhost/mini-master/home/documentation will execute documentation()method in application/controllers/Home.php.

The following links are only visible for logged in users.

  • http://localhost/mini-master/songs/add will call add() method in application/controllers/Songs.php.
  • http://localhost/mini-master/songs/listofsongs will do what the listOfSongs()method in application/controllers/Songs.php says.
  • http://localhost/mini-master/songs/editsong/28 will execute the editSong() method in application/controllers/Songs.php and will pass ’28’ as a parameter to it.

Showing a view

Let’s look at the documentation() method in application/controllers/Home.php: This simply shows the header, navbar, footer and the documentation.php page (in views/home/). If you need to do something like preparing data, you can add the needed code before loading the views.

<?php
    public function documentation() {
        // load views
        require APP . 'view/_templates/header.php';
        require APP . 'view/_templates/nav.header.php';
        require APP . 'view/home/documentation.php';
        require APP . 'view/_templates/footer.php';
    }
?>

Working with data

Let’s look into the listOfSongs() method in the application/controllers/Songs.php: Similar to documentation, but here we also request data. Again, everything is extremely reduced and simple: $this->model->getAllSongs() simply calls the getAllSongs() method in application/model/model.php.

<?php
    public function listOfSongs() {
        $this->loadModel('Songs');
        $songs = $this->model->getAllSongs();
        // load views. within the views we can echo out $songs
        require APP . 'view/_templates/header.php';
        require APP . 'view/_templates/nav.header.php';
        require APP . 'view/songs/listofsongs.php';
        require APP . 'view/_templates/footer.php';
    }
?>

The data-handling method for retreiving the list of songs from the database are in application/model/Songs.php. Have a look how getAllSongs() in Songs.php looks like.

<?php
    public function getAllSongs() {
        // get a database instance
        $db = new Database\Database();
        //connect to database
        $db = $db->connect();
        $all = $db->query()
        ->from('songs', array(
                'id',
                'artist',
                'track',
                'link'
        ))
        ->order('id', 'desc')
        ->all();
        //disconnect from database
        $db->disconnect();
        return $all;
    }
?>

The result, here $songs, can then easily be used directly inside the view files (in this case application/views/songs/listofsongs.php, in a simplified example):

<table class="table table-striped table-bordered table-hover table-condensed">
 <thead>
  <tr>
   <th class="text-center">Id</th>
   <th class="text-center">Artist</th>
   <th class="text-center">Track</th>
   <th class="text-center">Link</th>
   <th class="text-center"></th>
  </tr>
 </thead>
 <tbody>
 <?php foreach ($songs as $song) { ?>
  <tr>
   <td><?php if (isset($song['id'])) echo htmlspecialchars($song['id'], ENT_QUOTES, CHARSET); ?></td>
   <td><?php if (isset($song['artist'])) echo htmlspecialchars($song['artist'], ENT_QUOTES, CHARSET); ?></td>
   <td><?php if (isset($song['track'])) echo htmlspecialchars($song['track'], ENT_QUOTES, CHARSET); ?></td>
   <td>
   <?php if (isset($song['link'])) { ?>
    <a href="<?php echo htmlspecialchars($song['link'], ENT_QUOTES, CHARSET); ?>"><?php echo htmlspecialchars($song['link'], ENT_QUOTES, CHARSET); ?></a>
   <?php } ?>
   </td>
   <td>
    <div class="btn-toolbar" role="toolbar">
     <div class="btn-group btn-group-xs" role="group">
      <a class="btn btn-default" href="<?php echo URL . 'songs/deletesong/' . htmlspecialchars($song['id'], ENT_QUOTES, CHARSET); ?>" role="button" title="Delete">
       <span class="glyphicon glyphicon glyphicon-remove" aria-hidden="true"></span>
      </a>
      <a class="btn btn-default" href="<?php echo URL . 'songs/editsong/' . htmlspecialchars($song['id'], ENT_QUOTES, CHARSET); ?>" role="button" title="Edit">
       <span class="glyphicon glyphicon glyphicon-pencil" aria-hidden="true"></span>
      </a>
     </div>
    </div>
   </td>
  </tr>
 <?php } ?>
 </tbody>
</table>
							

Sending mail

For the emailing library, I have extended PHPMailer. This was done for simplicity. I just created the basic functions needed, added extra validations and called PHPMailer functions afterwards.

Sending an e-mail is quite easy and straight forward. Let’s look into the contactUs() method in application/controllers/Home.php. Simply specify a sender, add recipients, type a subject, and a body, and finally call the sendMail() menthod.

<?php
    $mailer = $this->emailer();
    $mailer->from(SMTP_USERNAME, 'MINI-FRAMEWORK-MVC');
    $mailer->addRecipient(SMTP_USERNAME, 'MINI-FRAMEWORK-MVC');
    $mailer->subject('This is a test');
    $mailer->replyTo('no-reply@miniframework.com', 'MINI-FRAMEWORK-MVC no-reply');
    $mailer->htmlBody(file_get_contents(APP . '\\view\_templates\_mail\contents.html'), APP . '\\view\_templates\_mail');
    $mailer->sendMail();
?>

Creating forms

Create forms with a base URL built from your config preferences. The main benefit of using this helper library rather than hard coding your own HTML, is that it permits your site to be more portable in the event your URLs ever change, and also, you will for sure know that all your forms are created in the same way.

Let’s stay in the contactus.php page (in views/home/). As you can see, there are a few basic step needed to create a form:

  1. Get an instance of the form helper
  2. Call the create() method to set the form properties
  3. Open the form by callling the open() method
  4. Start adding elements to your form. You can add several different elements such as labels, textboxes, drop-downs, etc.
  5. Close the form by calling the close() method
<?php
    //get an instance of the form helper
    $form = $this->form();

    //call the create()-method to set the form properties
    $form->create(array(
        'method' => 'post',
        'name' => 'formContactUs',
        'id' => 'formContactUs',
        'role' => 'form',
        'novalidate' => false
    ));

    //open the form for adding input controls
    $form->open();

    //start adding elements to your form. You can add several different elements such as labels, textboxes, drop-downs, etc.
    //...

    //close the form
    $form->close();
?>

Validating forms

We are still sticking to the contactUs.php page (in views/home/). Have a loook into the contactUs() method in the application/controllers/Home.php. The advantage of the form validation helper library is that you can define a set of rules and apply them to different elements in different pages.

To use them, follow these simple steps:

  1. Get an instance of the form validation helper library
  2. Always check that the form was submitted before validating the form elements’ values
  3. Set all the rules for each form element
  4. Call the run() method to validate each form element data
<?php
    // check that the form was submitted before validating the form elements' values
    if (isset($_POST['btnContactUs'])) {
        $validator = $this->formValidations();

        // set all the form rules
        $validator->setRule('subject', 'Subject', 'required|minLength[5]|maxLength[45]', array(
            'required' => 'Please specify a subject',
            'minLength' => 'Subject must be at least 5 characters',
            'maxLength' => 'Subject cannot be longer then 45 characters'
        ));
        $validator->setRule('name', 'Name', 'required|minLength[5]|maxLength[45]', array(
            'required' => 'Please specify your name',
            'minLength' => 'Name must be at least 5 characters',
            'maxLength' => 'Name cannot be longer then 45 characters'
        ));
        $validator->setRule('email', 'E-mail', 'required|email|maxLength[45]', array(
            'required' => 'Please specify your e-mail address',
            'email' => 'Correo electrónico no válido',
            'maxLength' => 'E-mail cannot be longer then 45 characters'
        ));
        $validator->setRule('message', 'Message', 'required|minLength[5]|maxLength[255]', array(
            'required' => 'Please specify your doubt, message or question',
            'minLength' => 'Message must be at least 5 characters',
            'maxLength' => 'Message cannot be longer then 255 characters'
        ));

        // do the validation
        if($validator->run('btnContactUs', 'contactUs') === false) {
            //do some confirmation
        }
    }
?>

Libraries

Database

NOTE: The following library and its helper classes are based on the example code from the book Pro PHP MVC by Chris Pitt. However, they were modified and adapted to meet some of the requirements not fulfilled by the code examples. For instance, is used PHP’s PDO class to handle the database connection and executing the SQL queries.

The database library is formed of two classes. The first class is the database factory, which is in charged of loading the needed database driver. There is no need to manually specify which type of database you are using, as it is taken from the configuration. Now, the second class is the query builder class, and it is responsible for building the vendor-specific database code. For the moment, these two classes support only MySQL database.

Database Access

The database configuration is done in the application/config/config.php file. Simply, modify the following parameter to suit your needs:

  • DB_TYPE: The type of database to connect to. Currently only MySQL is fully supported
  • DB_HOST: The IP of the server where the database is located
  • DB_NAME: The name of the database
  • DB_USER: The username used for connecting to the database
  • DB_PASS: The password used for connecting to the database
  • DB_CHARSET: The character set to used in the database

Once the database configuration is done, you can start using the library as follow:

<?php
    // get a database instance
    $db = new Database\Database();
    //connect to database
    $db = $db->connect();
    //get an instance of the query builder helper class for
    $builder = $db->query();
    //build your query and do something
    //...
    //disconnect from database
    $db->disconnect();
?>

Selecting Data

The following functions allow you to build SQL SELECT statements.

$db->query()->from(): Used for specifying the table from which the data should be written to, or read from, and the fields to read from or write to.

param $from (string):
Table from which the data should be written to, or read from.
param $fields (array):
An array containing the fields that would be queried. If the fields is an associative array, the key is the column name and the value is the alias. Default value is “*”.
return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $db->query()
        ->from('songs')
    // Produces: SELECT songs.* FROM songs
?>
<?php
    $db->query()
        ->from('songs', array(
            'id',
            'artist',
            'track',
            'link'
    ))
    // Produces: SELECT songs.id, songs.artist, songs.track, songs.link FROM songs
?>
<?php
    $db->query()
        ->from('songs', array(
            'id' => 'ID',
            'artist' => 'ARTIST',
            'track' => 'TRACK',
            'link' => 'LINK'
    ))
    // Produces: SELECT songs.id AS ID, songs.artist AS ARTIST, songs.track AS TRACK, songs.link AS LINK FROM songs
?>

$db->query()->get(): Executes the SQL query and returns data from the database.

param $distinct (boolean):
If set to true, the select query will use the distinct statement. If set to false, it will create a normal select query. Default is false
return:
An array with the rows found.

For example:

<?php
    $songs = $db->query()
                    ->from('songs')
                    ->get()
    // Produces: SELECT * FROM songs
?>

If the variable $distinct is set to true, the ‘DISTINCT’ keyword will be added to the query.

<?php
    $songs = $db->query()
                    ->from('songs')
                    ->get(true)
    // Produces: SELECT DISTINCT * FROM songs
?>

Notice that the above code snippets are assigned to a variable named $songs, which can be used to show the rows found:

<?php
    foreach ($songs as $song) {
        echo $song['id']
        echo $song['artist']
        echo $song['track']
        echo $song['link']
    }
?>

$db->query()->join(): Used to specify joins across tables.

param $type (string):
The type of join to use. possible values are null (default), ‘LEFT’, ‘RIGHT’, ‘OUTER’, ‘INNER’, ‘LEFT OUTER’, ‘RIGHT OUTER’. if null is used, a NATURAL join will be set
param $join (string):
Name of the to be joined table
param $on (string):
The condition to be met for the join. eg: table1.field = table2.field
param $fields (array):
An array containing the fields that would be queried from the joined table. If the fields i s an associative array, the key is the column name and the value is the alias. Default value is “*”.
return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $db->query()
        ->from('songs', array(
            'id' => 'ID',
            'artist' => 'ARTIST',
            'track' => 'TRACK',
            'link' => 'LINK'
        ))
        ->join(null, 'users', 'users.user_id = songs.id', array(
            'names',
            'lastnames',
            'email'
        ));
    // Produces: SELECT songs.id, songs.artist, songs.track, songs.link, users.names, users.lastnames, users.email FROM songs JOIN users ON users.user_id = songs.id
?>

$db->query()->limit(): Used for specifying how many rows to return at once, and on which page to begin the results.

param $imit (integer):
Number of rows to return at once
param $page (integer):
Page number to return the rows calculated as follow $limit * ($page – 1). Default value is 1.
return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $db->query()
        ->from('songs', array(
            'id' => 'ID',
            'artist' => 'ARTIST',
            'track' => 'TRACK',
            'link' => 'LINK'
        ))
        ->limit(5, 3);
    // Produces: SELECT songs.id, songs.artist, songs.track, songs.link FROM songs LIMIT 10, 5
?>

$db->query()->order(): Used for specifying which field to order the query by, and in which direction.

param $order (string):
Field by which the query will be ordered in the form of table.field or just the field
param $direction (string):
Direction in which the rows will be ordered. Default value is “ASC”
return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $db->query()
        ->from('songs')
        ->order('songs.id', 'DESC');
    // Produces: SELECT songs.* FROM songs ORDER BY songs.id DESC
?>

$db->query()->group(): Used for specifying the fields to group the query by.

param $fields (string):
An array with the fields in the form of table.field or just the field
return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $db->query()
        ->from('songs')
        ->order('songs.id', 'DESC')
        ->group(array('songs.id'));
    // Produces: SELECT songs.* FROM songs GROUP BY songs.id ORDER BY songs.id DESC
?>

$db->query()->select_first(): Get the first row from the result set specified by the query.

param $column (string):
The column from which to get the first value in the form of table.field or just the field
return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $db->query()
        ->from('songs')
        ->select_first('songs.id');
    // Produces: SELECT songs.* FROM songs ORDER BY songs.id ASC LIMIT 1
?>

$db->query()->select_last(): Get the last row from the result set specified by the query.

param $column (string):
The column from which to get the last value in the form of table.field or just the field
return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $db->query()
        ->from('songs')
        ->select_last('songs.id');
    // Produces: SELECT songs.* FROM songs ORDER BY songs.id DESC LIMIT 1
?>

$db->query()->select_avg(): Calculates the average value of a numeric column.

param $column (string):
The column from the table you wish to calculate the average in the form of table.field or just the field
param $alias (string):
Refering name for the result
return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $db->query()
        ->from('songs')
        ->select_avg('songs.id', 'AVG_ID');
    // Produces: SELECT AVG(songs.id) AS AVG_ID FROM songs ORDER BY songs.id ASC LIMIT 1
?>

$db->query()->select_count(): Counts the number of rows that matches a specified criteria.

param $column (string):
The column from the table you wish to count the rows in the form of table.field or just the field
param $alias (string):
Refering name for the result
return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $db->query()
        ->from('songs')
        ->select_count('songs.id', 'COUNT_ID');
    // Produces: SELECT COUNT(songs.id) AS COUNT_ID FROM songs ORDER BY songs.id ASC LIMIT 1
?>

$db->query()->select_max(): Calculates the largest value of the selected column.

param $column (string):
The column from the table you wish to get the largest value in the form of table.field or just the field
param $alias (string):
Refering name for the result
return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $db->query()
        ->from('songs')
        ->select_max('songs.id', 'MAX_ID');
    // Produces: SELECT MAX(songs.id) AS MAX_ID FROM songs ORDER BY songs.id ASC LIMIT 1
?>

$db->query()->select_min(): Calculates the smallest value of the selected column.

param $column (string):
The column from the table you wish to get the smallest value in the form of table.field or just the field
param $alias (string):
Refering name for the result
return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $db->query()
        ->from('songs')
        ->select_min('songs.id', 'MIN_ID');
    // Produces: SELECT MIN(songs.id) AS MIN_ID FROM songs ORDER BY songs.id ASC LIMIT 1
?>

$db->query()->select_sum(): Calculates the total sum of a numeric column.

param $column (string):
The column from the table you wish to get the total sum value in the form of table.field or just the field
param $alias (string):
Refering name for the result
return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $db->query()
        ->from('songs')
        ->select_sum('songs.id', 'MIN_ID');
    // Produces: SELECT MIN(songs.id) AS MIN_ID FROM songs ORDER BY songs.id ASC LIMIT 1
?>

Looking For Specific Data

$db->query()->where(): Allows for variable-length arguments. It will accept a string in the format of “foo=? AND bar=? OR baz=?” and take a further three arguments to replace those “?” characters. With them, it will run PHP’s “sprintf” function, and tokenize the string.

return:
A reference to the class instance, so that they can be chained.

For example:

<?php
    $songs = $db->query()
                    ->from('songs')
                    ->where('id = ?', 30)
                    ->get()
    //Produces: SELECT id, artist, track, link FROM songs WHERE id = '30'
?>

Inserting Data

$db->query()->insert(): Use for inserting data into database. Generates an insert string based on the supplied data, and executes the query.

param $data (array):
An associative array where the key es the database column name, and the value is the value to insert
return:
Last inserted Id in case an insert was requested

For example:

<?php
    $db->query()
        ->from('songs')
        ->insert(array(
            'artist' => $artist,
            'track' => $track,
            'link' => $link
        ));
    // Produces: INSERT INTO `songs` (`artist`, `track`, `link`) VALUES ('The artist', 'The track', 'The link')
?>

Updating Data

$db->query()->update(): Use for updating data. Generates an update string based on the supplied data, and executes the query.

param $data (array):
An associative array where the key es the database column name, and the value is the value to update
return:
The number of affected rows

For example:

<?php
    $db->query()
        ->from('songs')
        ->where('id = ?', $songId)
        ->update(array(
            'artist' => $artist,
            'track' => $track,
            'link' => $link
        ));
    // Produces: UPDATE songs SET artist = 'The artist', track = 'The track', link = 'The link' WHERE id = '37'
?>

Deleting Data

$db->query()->update(): Use for deleting database information. Generates delete string based on the supplied data, and executes the query.

return:
The number of affected rows

For example:

<?php
    $db->query()
        ->from('songs')
        ->where('id = ?', $songId)
        ->delete();
    // Produces: DELETE FROM songs WHERE id = '37'
?>

Executing SQL Statements

$db->query()->execute(): Executes the SQL query statment.

param $sql (string):
The SQL query to execute
return:
PDOStatement

For example:

<?php
    $db->query()->execute($sql)
?>

Email

NOTE: For the emailing library, PHPMailer library was extended and implemented. This was done for simplicity.

NOTE: You can use Gmail SMTP server to send mail, but you have to configure the Gmail accout that you will be using. Head over to Account Security Settings and enable “Access for less secure apps”, this allows you to use the google SMTP for clients other than the official ones.

Email Configuration

The email configuration is done in the application/config/config.php file. Simply, modify the following parameter to suit your needs:

  • IS_SMTP: Tells PHPMailer to use SMTP
  • MAIL_SERVER: Sets the hostname of the mail server
  • SMTP_PORT: Sets the SMTP port number – 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
  • SMTP_USERNAME: Username to use for SMTP authentication – use full email address for gmail
  • SMTP_PWD: Password to use for SMTP authentication
  • SMTP_DEBUG: Enable SMTP debugging: (0) = off (for production use); (1) = client messages; (2) = client and server messages. Default is 0
  • SMTP_SECURE: Set the encryption system to use – ssl (deprecated) or tls. Default is tls
  • SMTP_AUTH: Whether to use SMTP authentication. Default is true
  • MAIL_CHARSET: Sets the character set
  • DEBUG_OUTPUT: Ask for HTML-friendly debug output. Default is html

Sending Mail (Basic)

For example:

<?php
    //get an instance of the mail library
    $mailer = $this->emailer();
    //specify some senders
    $mailer->from(mini.framework.mvc@gmail.com, 'MINI-FRAMEWORK-MVC');
    //specify some recipients
    $mailer->addRecipient('john.doe@gmail.com', 'John Doe');
    //specify a mail subject
    $mailer->Subject = 'This is a test';
    //specify the body
    $mailer->msgHTML(file_get_contents(APP . '\\view\_templates\_mail\contents.html'), APP . '\\view\_templates\_mail');
    //send the mail
    $mailer->sendMail();
?>

File Upload

The File Upload library will help you with the uploading of files to your server. Similar to other libraries, you can set various preferences, restricting the type and size of the files.

The following preferences are available in the application/config/config.php file. Simply, modify the following parameter to suit your needs:

  • UPLOAD_PATH: The path to the directory where the upload should be placed. The directory must be writable and the path can be absolute or relative
  • UPLOAD_ALLOWED_EXTENSIONS: An array corresponding to the types of files you allow to be uploaded. The file extension can be used as the mime type
  • UPLOAD_FILENAME: If set, the uploaded file will be renamed to this name. The extension provided in the file name must also be an allowed extension type. If no extension is provided, the one provided in the original file will be used
  • UPLOAD_ENCRYPT_FILENAME: If true, the filename will be replace with an encrypted random filename
  • UPLOAD_MAX_FILESIZE: The maximum size (in kilobytes) that the file can be. Set to zero for no limit. Note: Most PHP installations have their own limit, as specified in the php.ini file. Usually 2 MB (or 2048 KB) by default

When getting an instance of this class from the controller, you can specify an array as an argument, which will override the configuration specified in the application/config/config.php file. If no argument is passed, the instance will be configured with the default values.

<?php
    $config = array(
            'uploadPath' => '../public/img/',
            'allowedExtension' => serialize (array ('jpg', 'jpeg', 'png')),
            'filename' => '',
            'encrypt' => 'true',
            'maxFilesize' => '10000000'
    );

    $uploaded = $this->upload($config);
?>

The configuration can be changed by calling the setter of each individual property.

$this->upload()->doUpload(): Uploads the file specified by $file. If $filename is specified, the uploaded file is renamed. Returns true if the file was successfully uploaded, otherwise false

param $file (array|$_FILE):
the file that will be uploaded
param $filename (string):
if specified, the name to which the file must be renamed to
return:
true if the file was successfully uploaded, otherwise false

For example:

<?php
    $this->upload()->doUpload();
?>

Form and Validations

Form Library

Programatically create forms with a base URL built from your config preferences. It will optionally let you add form attributes hidden input fields, and will always add the accept-charset attribute based on the charset value in your config file, if not specified.

The main benefit of using this tag rather than hard coding your own HTML is that it permits your site to be more portable in the event your URLs ever change.

Form Available Functions

$this->form()->create(): Creates an opening form tag with all the attributes passed from the $this->form-create() method.

param $attributes (array):
An associative array of attributes used to configure the form. The key is the property, and the value is the value to assign.

Accepted properties are:

  • charset: Charset used in the submitted form (default: the page charset)
  • action: An address (url) where to submit the form (default: the submitting page)
  • autocomplete: If the browser should autocomplete the form (default: on)
  • enctype: The encoding of the submitted data (default: is url-encoded)
  • method: The HTTP method used when submitting the form (default: GET)
  • name: A name used to identify the form (for DOM usage: document.forms.name)
  • novalidate: Tells the browser should not validate the form
  • target: The target of the address in the action attribute (default: _self)
  • classes: A string with the CSS classes to use
  • role: The role of the form. Useful for material design frameworks

For example:

<?php
    $this->form()
            ->create(array(
                'method' => 'post',
                'name' => 'formContactUs',
                'id' => 'formContactUs',
                'role' => 'form',
                'classes' => 'form-horizontal',
                'novalidate' => false
            ));
?>

$this->form()->open(): Creates an opening form tag with all the attributes passed from the $this->form-create() method.

For example:

<?php
    $this->form()->open();
    // Produces:     <form method="post" name="formContactUs" id="formContactUs" role="form" novalidate="">
    // based on the parameters from the call of $this->form-create() method
?>

$this->form()->close(): Produces a closing form tag. The only advantage to using this function is it permits you to pass data to it which will be added below the tag.

param $extra (string):
Anything to append after the closing tag, as is

For example:

<?php
    $this->form()->close();
    // Produces: </form>
?>

$this->getFormData(): This is a global function that lets you retrieve a value that was submitted when sending a form.

param $field (string):
The name of the submitted data to get.
return:
The value of the field or null.

$this->clearFormData(): This is a global function that lets you unset or clear the $_POST and/or $_GET global variables.

Input Shared Attributes

When creating an input element for a form, it is required to pass an associative array with the attributes used to configure it, and where the key is the property, and the value is the value to assign. The library does not filter any key of the array, but when rendering the input element, it will only render those valid for the specific input element.

Neverthless, there are some attributes that are specific to a type of input element. Those attributes will be explained in its respective section.

The shared attributes are:

  • classes (string): A string with the CSS classes to use
  • style (string): The stye use for styling the input field
  • placeholder (string): A hint that describes the expected value of an input field
  • id (string): The identification of the input field
  • name (string): The name of the input field
  • value (string/integer/float/etc): The default value for an input field
  • disabled (boolean): The input field is disabled. A disabled element is un-usable and un-clickable. Disabled elements will not be submitted. Default is false (not disabled)
  • readonly (boolean): The input field is read only (cannot be changed). Default is false (not readonly)
  • multiple (boolean): Boolean attribute. When present, it specifies that the user is allowed to enter more than one value. Default is false (not multiple)
  • required (boolean): Boolean attribute. When present, it specifies that an input field must be filled out before submitting the form. Default is false (not required)
  • min (integer/float): The minimum value for an input field
  • max (integer/float): The maximum value for an input field
  • maxlength (integer): The maximum number of character for an input field. With a maxlength attribute, the input control will not accept more than the allowed number of characters
  • size (integer): The width (in characters) of an input field
  • pattern (string): A regular expression that the input element’s value is checked against
  • step: Legal number intervals for an input field
  • title (string): Extra information about an element
  • data (string): The data-* attributes is used to store custom data private to the page or application.

Input Available Functions

$this->form()->formButton(): Lets you generate a standard submit button.

param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formButton(array(
                'id' => 'btnRegister',
                'name' => 'btnRegister',
                'value' => 'register',
                'classes' => 'btn btn-primary btn-lg text-center',
                'text' => 'Register'
            ));
    // Produces: <button id="btnRegister" name="btnRegister" value="register" class="btn btn-primary btn-lg text-center" type="submit">Register</button>
?>

$this->form()->formCheckbox(): Lets you generate a checkbox input fields. These are the two specific variables that need to included in the variable $attibutes and that are needed for creating an input element:

  • text (string): The text associated to the checkbox
  • checked (boolean): Whether the checkbox should be checked or not. Default is false (not checked)
param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formCheckbox(array(
                'id' => 'gender',
                'name' => 'gender',
                'value' => 'female',
                'text' => 'Female'
            ));
    // Produces: <input id="gender" name="gender" value="female" type="checkbox">Female
?>

$this->form()->formDatePicker(): Lets you generate a datepicker input fields. However, since not all the Web navigators have native support for date input element, we have implemented Datepicker for Bootstrap by Stefan Petre. For simplification, these eight specific variables were created and should be included in the variable $attibutes when creatig a date picker input element:

  • format (string): The date format, combination of d, dd, D, DD, m, mm, M, MM, yy, yyyy
  • autoClose (boolean): Whether or not to close the datepicker immediately when a date is selected
  • clearBtn (boolean): If true, displays a “Clear” button at the bottom of the datepicker to clear the input value. If “autoclose” is also set to true, this button will also close the datepicker
  • language (string): The IETF code of the language to use for month and day names
  • todayHighlight (boolean): If true, highlights the current date
  • orientation (string): A space-separated string consisting of one or two of “left” or “right”, “top” or “bottom”, and “auto” (may be omitted)
  • forceParse (boolean): Whether or not to force parsing of the input value when the picker is closed
  • assumeNearbyYear (boolean/integer): If true, manually-entered dates with two-digit years. To configure the number of years in advance that the picker will still use the current century, use an Integer instead of the Boolean true.

NOTE: If you would like a deeper description of the widget options, please visit the officla site by clicking on this link Datepicker for Bootstrap by Stefan Petre.

If you prefer, you can directly use the data property and send it using the $attributes array. It does the same thing as the specific defined properties, but also it gives you the possiblity to use the rest of the options allowed by this widget.

param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formDatePicker(array(
                'id' => 'birthday',
                'name' => 'birthday',
                'placeholder' => 'Birthday',
                'classes' => 'form-control input-controls',
                'format' => 'dd/mm/yyyy',
                'clearBtn' => 'true',
                'language' => 'en',
                'todayHighlight' => 'true',
                'orientation' => 'left bottom',
                'forceParse' => 'true',
                'assumeNearbyYear' => '20',
                'value' => ''
            ));
    // Produces:    <input id="birthday" name="birthday" placeholder="Birthday" class="form-control input-controls" 
    //                    data-date-format="dd/mm/yyyy" data-date-clear-btn="true" data-date-language="en" 
    //                    data-date-today-highlight="true" data-date-orientation="left bottom" data-date-force-parse="true" 
    //                    data-date-assume-nearby-year="20" value="" type="text" data-provide="datepicker">
?>

$this->form()->formDropDown(): Lets you generate a dropdown select input field. These are the two specific variables that need to included in the variable $attibutes and that are needed for creating an input element:

  • options (array): An associative array of options, were the key is the value of the option and the value is the text of the option
  • selected (string): The value you wish to be selected. Field to mark with the selected attribute
param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formDropDown(array(
                'id' => 'agree',
                'name' => 'agree',
                'classes' => 'form-control input-controls',
                'options' => array(
                    'yes' => 'Yes',
                    'no' => 'No'
                ),
                'selected' => 'no'
            ));
    // Produces:    <select id="agree" name="agree" class="form-control input-controls">
    //                    <option value="yes">Yes</option>
    //                    <option value="no" selected="selected">No</option>
    //                </select>
?>

$this->form()->formHidden(): Lets you generate hidden input fields.

param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formHidden(array(
                'id' => 'hiddenField',
                'name' => 'hiddenField',
                'value' => 'invisible'
            ));
    // Produces: <input id="hiddenField" name="hiddenField" value="invisible" type="hidden">
?>

$this->form()->formLabel(): Lets you generate a standard label. There is only a single specific variables that need to included in the variable $attributes and that is needed for creating an input element:

  • for (string): Specifies which form element a label is bound to
param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formLabel(array(
                'for' => 'birthday',
                'classes' => 'sr-only',
                'text' => 'Birthday'
            ));
    // Produces: <label for="birthday" class="sr-only">Birthday:</label>
?>

$this->form()->formMail(): Lets you generate an email input field

param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formMail(array(
                'id' => 'email',
                'name' => 'email',
                'placeholder' => 'E-mail',
                'classes' => 'form-control input-controls',
                'value' => ''
            ));
    // Produces: <input id="email" name="email" placeholder="E-mail" class="form-control input-controls" value="" type="email">
?>

$this->form()->formNumber(): Define a field for entering a number (You can also set restrictions on what numbers are accepted). Use the following attributes to specify restrictions:

  • min (integer): Specifies the minimum value allowed
  • max (integer): Specifies the maximum value allowed
  • step (integer): Specifies the legal number intervals
  • value (integer): Specifies the default value
param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formNumber(array(
                'id' => 'count',
                'name' => 'count',
                'classes' => 'form-control input-controls',
                'min' => '0',
                'max' => '5',
                'step' => '1',
                'value' => '0'
            ));
    // Produces: <input id="count" name="count" class="form-control input-controls" min="0" max="5" step="1" value="0" type="number">
?>

$this->form()->formPassword(): Lets you generate a password input fields. The show/hide password plugin by Zhixin Wen can be enabled by including the following properties in the variable $attibutes when creatig a password input element:

  • toggle (boolean): Activate the show/hide password plugin
  • message (string): The tooltip of show/hide icon. Default value is “Click here to show/hide password”
  • placement (string): The placement of show/hide icon, can be ‘before’ or ‘after’. Default is ‘after’
param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

NOTE: If you would like a deeper description of the widget options, please visit the official site by clicking on this link show/hide password plugin by Zhixin Wen.

If you prefer, you can directly use the data property and send it using the $attributes array. It does the same thing as the specific defined properties, but also it gives you the possiblity to use the rest of the options allowed by this widget.

For example:

<?php
    $this->form()
            ->formPassword(array(
                'id' => 'password',
                'name' => 'password',
                'placeholder' => 'Password',
                'classes' => 'form-control input-controls',
                'placement' => 'after',
                'message' => 'Show/Hide password',
                'toggle' => true
            ));
    // Produces:     <input id="password" name="password" placeholder="Password" class="form-control input-controls" data-placement="after"
    //                data-message="Show/Hide password" data-toggle="password" type="password">
?>

$this->form()->formRadio(): Lets you generate a radio input field. These are the two specific variables that need to included in the variable $attributes and that are needed for creating an input element:

  • text (string): The text associated to the radio
  • checked (boolean): Whether the radio should be checked or not. Default is false (not checked)
param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formRadio(array(
                'id' => 'gender',
                'name' => 'gender',
                'value' => 'female',
                'text' => 'Female'
            ));
    // Produces: <input id="gender" name="gender" value="female" type="radio">Female
?>

$this->form()->formRange(): Define a control for entering a number whose exact value is not important (like a slider control). Depending on browser support, the input field can be displayed as a slider control. You can also set restrictions on what numbers are accepted Use the following attributes to specify restrictions:

  • min (integer): Specifies the minimum value allowed
  • max (integer): Specifies the maximum value allowed
  • step (integer): Specifies the legal number intervals
  • value (integer): Specifies the default value
param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formRange(array(
                'id' => 'count',
                'name' => 'count',
                'classes' => 'form-control input-controls',
                'min' => '0',
                'max' => '5',
                'step' => '1',
                'value' => '0'
            ));
    // Produces: <input id="count" name="count" class="form-control input-controls" min="0" max="5" step="1" value="0" type="range">
?>

$this->form()->formTextarea(): Lets you define a multi-line text input control. Use the following attributes to specify restrictions:

  • cols (integer): Specifies the visible width of a text area
  • rows (integer): Specifies the visible number of lines in a text area
  • wrap (integer): Specifies how the text in a text area is to be wrapped when submitted in a form. Posible values are hard or soft
param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formTextarea(array(
                'id' => 'message',
                'name' => 'message',
                'placeholder' => 'Message',
                'classes' => 'form-control input-controls',
                'rows' => '5',
                'value' => 'This is the value'
            ));
    // Produces: <textarea id="message" name="message" placeholder="Message" class="form-control input-controls" rows="5" value="This is the value">This is the value</textarea>
?>

$this->form()->formTextbox(): Lets you generate a standard text input field.

param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formTextbox(array(
                'id' => 'subject',
                'name' => 'subject',
                'placeholder' => 'Subject',
                'classes' => 'form-control input-controls',
                'value' => ''
            ));
    // Produces: <input id="subject" name="subject" placeholder="Subject" class="form-control input-controls" value="" type="text">
?>

$this->form()->formUpload(): Lets you generate a standard browser input field. Defines a file-select field and a “Browse…” button (for file uploads). Use the following attributes to specify restrictions:

  • accept (string): Specifies the types of files that the server accepts (that can be submitted through a file upload)
param $attributes (array):
An associative array of attributes used to configure the input element. The key is the property, and the value is the value to assign.

For example:

<?php
    $this->form()
            ->formUpload(array(
                'id' => 'uploadFile',
                'name' => 'uploadFile',
                'classes' => 'form-control input-controls',
                'accept' => '.sql'
            ));
    // Produces: <input id="uploadFile" name="uploadFile" class="form-control input-controls" accept=".sql" type="file">
?>

Validation Library

Before we go into explaining how to create form validation rules, lets revise the step needed for submitting a valid form.

  1. You go to a specific page and a form is displeyed.
  2. You fill in the form and submit it.
  3. If the submitted values are not valid, e.g. there are some empty value, you are redirected back to the same page, and the form is again displayed but now including your previously submitted data, and of course some error messages on those fields with invalid data.
  4. This process is repeated until the all the validations are passed, and no incorrect data is sent.

All those rule validations are run on the server side. Each form field has predefied validations rules that must be meet in order to be a valid value. Lets have a look at the different rules available.

$this->formValidations()->setRule(): This function sets the conditions that a specific form field must fulfil in order to be valid.

param $field (string):
The name of the form field to validate
param $attributes (string):
The label to used for displaying the error message in reference to $field
param $rules (mixed):
The conditions that determine if $field is valid or not. It can be a string delimeted by | or an array
param $errors (array):
An associative array with the message that must be shown if the condition is not met

For example:

<?php
    $this->formValidations()
            ->setRule('subject', 'Subject', 'required|minLength[5]|maxLength[45]', array(
                'required' => 'Please specify a subject',
                'minLength' => 'Subject must be at least 5 characters',
                'maxLength' => 'Subject cannot be longer then 45 characters'
            ));
?>

$this->formValidations()->run(): Executes the form validation, but only if the submit button name and value equals to the parameters. These parameters are needed in case there are multiple form in the same page.

param $button (string):
The name of the button that will submit the form
param $value (string):
The value that is sent by the submit button
return:
true if errors were found, false if it not

For example:

<?php
    if($this->formValidations()->run('btnContactUs', 'contactUs') === false) {
        // do something as there were no errors found in the submitter form
    }
?>

$this->formValidations()->getErrors(): Returns an associative array with all the fields that were submitted with an incorrect value. The key is the field and the value is an array containing all the error related to that field.

For example:

<?php
    $errors = $this->formValidations()->getErrors();
?>

Supported Rules

Rule Parameter Description Example
alphaNumeric No Returns FALSE if the form element contains anything other than alpha-numeric characters
date No Returns TRUE if the date given is valid; otherwise returns FALSE
differs Yes Returns TRUE if the two values are different; otherwise returns FALSE differs[form_item]
email No Returns TRUE if the email is a valid one; otherwise returns FALSE
greaterOrEqualThan Yes Returns FALSE if the form element is greater than or equal to the parameter value or not numeric greaterOrEqualThan[81]
greaterThan Yes Returns FALSE if the form element is greater than the parameter value or not numeric greaterThan[33]
inList Yes Returns FALSE if the form element is not within a predetermined list inList[euro,dolar,quetzal]
ip No Returns FALSE if the supplied IP is not valid, otherwise TRUE
lessOrEqualThan Yes Returns FALSE if the form element is less than or equal to the parameter value or not numeric lessOrEqualThan[81]
lessThan Yes Returns FALSE if the form element is less than the parameter value or not numeric lessThan[6]
matches Yes Returns FALSE if the form element does not match the one in the parameter, otherwise TRUE matches[form_item]
maxLength Yes Returns FALSE if the form element is longer than the parameter value or not numeric maxLength[10]
minLength Yes Returns FALSE if the form element is shorter than the parameter value or not numeric minLength[5]
numeric No Returns FALSE if the form element contains anything other than numeric characters, otherwise TRUE
required No Returns FALSE if the form element is empty, otherwiser TRUE
url No Returns FALSE if the form element does not contain a valid URL

Image Manipulation

The Image Manipulation librarylets you perform the following actions: image resize and thumbnail creation.

The following preferences are available in the application/config/config.php file. Simply, modify the following parameter to suit your needs:

  • IMG_QUALITY: Ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file)
  • IMG_COMPRESSION_LEVEL:
  • IMG_MAX_WIDTH: The maximum width (in pixels) that the image can be. Set to zero for no limit
  • IMG_MAX_HEIGHT: The maximum height (in pixels) that the image can be. Set to zero for no limit
  • IMG_THUMBNAIL_FOLDER:
  • IMG_THUMB_MAX_WIDTH: The maximum width (in pixels) that the thumbnail image can be. Set to zero for no limit
  • IMG_THUMB_MAX_HEIGHT: The maximum height (in pixels) that the thumbnail image can be. Set to zero for no limit

When getting an instance of this class from the controller, you can specify an array as an argument, which will override the configuration specified in the application/config/config.php file. If no argument is passed, the instance will be configured with the default values.

<?php
    $config = array(
            'quality' => 100,
            'compressionLevel' => 9,
            'maxWidth' => 1380,
            'maxHeight' => 920,
            'thumbnailFolder' => '../public/img/thumbs/',
            'thumbMaxWidth' => 314,
            'thumbMaxHeight' => 209
    );

    $image = $this->image($config);
?>

The configuration can be changed by calling the setter of each individual property.

$this->image()->resize(): Resizes an image file to the values specified by IMG_MAX_-WIDTH and -HEIGHT

param $filename (string):
The name of the image including the path
return:
true on success, otherwise false

For example:

<?php
    $this->image()->resize('../img/new_image.png');
?>

$this->image()->thumbnail(): Creates an image thumbnail of size specified by IMG_THUMB_MAX_-WIDTH and -HEIGHT

param $filename (string):
The name of the image including the path
return:
true on success, otherwise false

For example:

<?php
    $this->image()->thumbnail('../img/new_image.png');
?>

Pagination

The Pagination library creates a large block of connected links which indicate a series of related content exists across multiple pages.

The following preferences are available in the application/config/config.php file. Simply, modify the following parameter to suit your needs:

  • NUMBER_OF_ITEMS_PER_PAGE: Max number of items to list in each page
param $currentPage (integer):
current page number. Default value is 0.
param $totalNumberOfItems (integer):
the total number of items that are in the whole list. Default value is 0.
param $numberOfItemsPerPage (integer):
the total number of items that will be displayed per page. Default value is NUMBER_OF_ITEMS_PER_PAGE.
param $url (string):
the root URL to which the links should point to. Default value is URL

For example:

<?php
    $pagination = $this->pagination($currentPage, $totalNumberOfItems, $numberOfItemsPerPage, $url);

    // Call this method if you are using Bootstrap v3
    $this->pagination()->renderBootstrapV3();

    // Call this method if you are using Bootstrap v4
    $this->pagination()->renderBootstrapV4();
?>

Session

This library is useful for maintaining the user’s current “state” and keep track of its activity while visiting your Web site. Because sessions run globally with each page load, a good place for using them would be in the controller.

Before start using the session library, configure the variable MAX_INACTIVE_SESSION in the application/config/config.php file. Simply, modify the following parameter to suit your needs:

  • MAX_INACTIVE_SESSION: The maximum number of seconds a session can be inactive

In the following code snippet, we use the session library to validate that there are some session variables already set and that the session has not been unactive for more then the number of seconds specified in the configuration variable MAX_INACTIVE_SESSION.

<?php
    //get an instance of the session library
    $session = $this->session();

    //varify that the session variables SID and email exists
    if($session->hasVariable('SID') && $session->hasVariable('email')) {
        //varify that the session has not been inactive for more than MAX_INACTIVE_SESSION seconds
        if($session->isSessionActive()) {
            //do something for the valid session
        }
    }

    //do something for the invalid session
?>

The above example can be use for restricting access to a controller if a user is not logged in for instance.

$this->session()->isSessionDisable(): Checks if the session is disabled or not. Returns true if the session is disable, false otherwise.

return:
true if the session is disable, false otherwise

For example:

<?php
    $this->session()->isSessionDisable();
?>

$this->session()->isSessionActive()

Checks if the session is active. A session is considered active if:

  1. sessions are enabled, but none exists; or
  2. sessions are enabled, and one exists; and
  3. the difference between the session’s creation timestamp and the current timestamp is less than the value specified by the constant MAX_INACTIVE_SESSION
return:
true if the sessions are enabled, false otherwise

For example:

<?php
    $this->session()->isSessionActive();
?>

$this->session()->setVariable()

Creates and sets a session variable. The function accepts a string or an associative array, where the key is the variable name and the value is the actual value of the variable.

param $data (string|array):
if $data is a string, it is considered as the session variable name
param $value (string):
value of the session variable. Only used if $data is a string
return:
true if the sessions are enabled, false otherwise

Here is an example of setting a variable when the parameter is a string:

<?php
    //sets the variable name with the value of Luis
    $this->session()->setVariable('name', 'Luis');
?>

And here is an example of setting a variable by passing an associative array:

<?php
    //sets the variable name with the value of Pedro and the variable lastname to Doe
    $this->session()->setVariable(array(
        'name' => 'Pedro',
        'lastname' => 'Doe'));
?>

$this->session()->unsetVariable()

Unsets a session variable but only if exists.

param $data (string|array):
if $data is a string, it is considered as the session variable name
return:
an instance of the class for chaining

Here is an example of setting a variable when the parameter is a string:

<?php
    //unsets the variable name
    $this->session()->unsetVariable('name');
?>

And here the variables name and lastname are unset:

<?php
    //unsets the variables name and lastname
    $this->session()->unsetVariable(array(
        'name', 'lastname'));
?>

$this->session()->hasVariable()

Checks if a session variable exists.

param $key (string):
The name of the variable which needs to be verified of its existance
return:
true if it exists, false otherwise

For example:

<?php
    $this->session()->hasVariable('name');
?>

$this->session()->getVariable()

Gets the value of a session variable.

param $key (string):
The name of the variable which needs to be verified of its existance
return:
The value of the session variable if it exists, false otherwise

For example:

<?php
    $this->session()->getVariable('name');
?>

$this->session()->regenerateId()

Update the current session id with a newly generated one. It will replace the current session id with a new one, and keep the current session information.

param $deleteOldSession (boolean):
Whether to delete the old associated session file or not. Default is true
return:
true on success, false otherwise

For example:

<?php
    $this->session()->regenerateId(false);
?>

$this->session()->sessionId()

Get and/or set the current session id.

return:
The session id for the current session or the empty string (“”) if there is no current session (no current session id exists)

For example:

<?php
    $this->session()->sessionId();
?>

$this->session()->destroySession()

Destroys current session.

For example:

<?php
    $this->session()->destroySession();
?>

$this->session()->createSession()

Creates the user’s session. It automatically generates a session variable called SID with the id of the current session. In addition, you can add other session variables by passing the $data parameter.

param $data (array):
An associative array where the key is the variable name and the value is the value of the variable
return:
true if the session was successfully created, false otherwise

For example:

<?php
    $this->session()->createSession(array(
        'username' => 'john.doe',
        'email' => 'john.doe@live.es'));
    //Creates three session variables: (1) SID; (2) username with the provided value; and (3) email with the provided value
?>

Other Contributions

As an open source enthusiastic, I like to share my projects. Hoping that they will be useful to anybody, just as other projects have been to me. The projects can be downloaded from my GitHub repository. Below is a short list of some of my contributions.

About canchitodev

Professional with solid experience in software development and management, leadership, team-building, workflow design and technological development. I consider myself a proactive, creative problem-solver, results-driven and with exceptional interpersonal skills person, who likes challenges, working as part of a team, and in high demanding environments. In these last few years, my career has focused on software management, development and design in the Media Broadcasting for television stations, thus allowing the automation of workflows

This site uses Akismet to reduce spam. Learn how your comment data is processed.