1. Basic usage of Arrayer class - adwins/Arrayer GitHub Wiki
1. Basic usage of Arrayer class.
Arrayer class has an idea to make a work with different string array data (such as POST data) easier.
Here there are some examples how to use it.
/**
* Creating a new Arrayer object based on $_POST variable.
*/
$post = new Arrayer;
/**
* Now $post is a collection of objects picked up from $_POST array.
*
* Suppose, we have recieved a web form like this:
* <form method="post" action="">
* <input name="username" />
* <input name="email" />
* <input name="age" />
* <input name="password" />
* <input name="repassword" />
* <select name="country">
* <option value="RU">Russia</option>
* <option value="DE">Germany</option>
* <option value="US">USA</option>
* <option value="MX">Mexico</option>
* <option value="CN">China</option>
* </select>
* </form>
*
* Then, we can achieve those values in this way:
*/
echo 'Your username is ' . $post->username . '<br />';
echo 'Your age is ' . $post->age . '<br />';
/**
* At this time $post->username is an Arrayer object, too.
* Now you can do some manipulations with it.
*
* For example, the Array::clean() method cleans the value from
* leading spaces and tabs, repeated newlines, etc.
*/
$post->username->clean();
/**
* If we had username equal to "John Smith", now we have got "John Smith".
*/
/**
* It is worth noting, all variables passed to Arrayer constructor are already trimmed
* by method Arrayer::trim().
*/
/**
* You can also do group operations like this:
*/
$post->clean();
/**
* All values of $post are now clean.
*/
/**
* Some other example:
* Let's get an MD5 hash of password.
*/
$password_hash = $post->password->md5();
/**
* Or even twice:
*/
$password_hash= $post->password->md5()->md5();
/**
* First of all, when you are getting POST data, you need to check the values.
* Method Arrayer::check() returns an Arrayer object in any case whether checked variable exists or does not.
*/
$post->check('username');
/**
* If $_POST['username'] (and so $post->username) does not exist, it will be defined
* and no error will occur when you try to call a method on it.
*
* You can also provide a default value when checking:
*/
$post->check('country', 'RU');
/**
* For those cases when you need to check some expected values,
* you can check it like this:
*/
if (!$post->country->in('RU', 'DE', 'US', 'MX', 'CN')){
$post->country = 'RU';
}
/**
* You can combine methods to check a variable and its value:
*/
if ($post->check('username')->is_empty()){
echo 'Username is empty<br />';
}
if (!$post->check('email')->is_email()){
echo 'Email is not valid<br />';
}
if (!$post->check('age')->is_number()){
echo 'Age is not number<br />';
}
if (!$post->check('age')->in_range(10, 90)){
echo 'Age is outbound<br />';
}
if (!$post->check('password')->is($post->check('repassword'))){
echo 'Passwords are misspelled<br />';
}
/**
* You can also add some extra post values.
*/
$post->extrafield = 'Some value';