The easiest way in which we can reuse our own code, or other's code, is by creating a helper and functions inside it. For example, take this code:
$user = "demo_user"; preg_match('/^[a-z\d_]{6,12}$/i', $user);
This is a useful piece of code, a regular expression it will check that a string has between 6 and 12 alphabetic characters, decimal numbers, or underscores. With this expression we could, for example, check usernames.
If we would like to have this code available for every controller of our site, we could put it into a helper. Our helpers are placed inside application/helpers
. We can call the file common_helper.php
. Place this code into it:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); if ( ! function_exists('validate_user')) { function validate_user($user) { if (preg_match('/^[a-z\d_]{6,12}$/i', $user)) { $validate = "Ok"; } else { $validate = "Ko"; } return $validate; } }
In addition to the code we have seen before, there are some other...