Creating Simple User Management

Erstellt am: Tuesday 31 January 2017  |  Letzte Änderung am: Wednesday 20 March 2019

Here you can learn how to build a user management with ItemManager in a simple way. This article is a part of the Working with ItemManager series. Be sure to read this article once you're comfortable with the basics: ItemManager API Reference - ItemManager class.

ItemManager is very well suited for the development of the user administration applications within GetSimple CMS. In this example I build a simple user administration script with the user registration and a confirmation mail, so that you can recognize the possibilities and adapt the script to your needs.

Creating Category:

Navigate to Categories menu, insert new category name Users and click Add category button:

Creating fields:

Add some new fields to the Users category:

  • email (Text field)
  • password (Password)
  • role (Dropdown box)
    • Guest
    • Admin
    • Superuser

You can add as many additional fields as you like, in my example the listed fields will suffice:

Well, you can already create the new users in the admin area, but it's not really fun yet. Instead, we make a simple user registration and let the system automatically register the user after an e-mail confirmation. Our user management will consist of a Controller, Processor and the View class, one template file user-admin.php and a functions.php file.

Let's look at the structure of the project, it's really simple:

theme/
│
└──your-theme/
   │
   │  functions.php
   │  user-admin.php
   │  ...
   │
   └──useradmin/
      │
      │  .htaccess
      │  Processor.php
      │  Controller.php
      │  View.php

If the file functions.php does not yet exist in your theme directory, you have to create 6 new files and a folder useradmin. If the functions.php already exist, you have to create 5 new files and a folder, you can use existing functions.php and put your code into the file below the existing functions.

Our script needs different areas (called sections) we'll use the GS pages for this purpose, let's create new pages with these slugs:

  • login (There we show the login form)
  • registration (The registration form will be shown there)
  • confirmation (The email confirmation page)
  • logout (This page is only needed as an action)
  • user (This is the user's private area)

Important, assign user-admin.php as a template to all these pages. The Use Fancy URLs should be enabled in GS settings!

Add an .htaccess file to the useradmin/ directory, it's not necessary because we code object oriented, just in case...

# Block access to any files
Deny from all

Let's have a look at the template file user-admin.php (in this tutorial I will use UIkit for layout and styling):

<?php if(!defined('IN_GS')){ die('you cannot load this page directly.'); } ?>
<!DOCTYPE html>
<html>
	<head>
		<title>User management with ItemManager</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<!-- UIkit CSS -->
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.9/css/uikit.min.css" />
		<!-- UIkit JS -->
		<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.9/js/uikit.min.js"></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.9/js/uikit-icons.min.js"></script>
	</head>
	<body>
	    <div class="uk-section">
		    <div class="uk-container uk-container-small">
			    <h1>User management with ItemManager</h1>
			    <?php
			    echo $view->renderMessages();
			    echo $view->renderContent();
			    ?>
		    </div>
	    </div>
	</body>
</html>

Each time a page is loaded, the View method renderContent() is called in the template. The View then checks the instructions from the Processor and depending on the requested page area renders it. Our View.php file looks like this:

<?php namespace UserAdministrator;

/**
 * Class View
 * @package UserAdministrator
 *
 * The View is the part of the user management script
 * where the HTML is generated and displayed.
 *
 */
class View
{
    /**
     * @var object Processor|null
     */
    private $processor = null;

    /**
     * @var object TemplateEngine|null
     */
    private $tplp = null;

    /**
     * View constructor.
     *
     * @param $processor
     */
    public function __construct($processor) {
        $this->processor = $processor;
        $this->tplp = $this->processor->imanager->getTemplateEngine();
    }

    /**
     * Content rendering function.
     * Depending on the section, a certain page area is rendered
     *
     */
    public function renderContent()
    {
        // Isn't a legale section
        if(!$this->processor->section) return;

        $method = 'gen'.ucfirst($this->processor->section);
        if(method_exists($this, $method)) {
            $section = $this->$method();
            return $this->tplp->render($section, $this->processor->data,
                true, array(), true
            );
        }
    }

    /**
     * This method looks for messages from the processor,
     * if there are any, they will be rendered and returned.
     *
     * @return string|void
     */
    public function renderMessages()
    {
        // No messages available
        if(!$this->processor->messages) return;

        $messages = '';
        foreach($this->processor->messages as $message) {
            $messages .= $this->genMessage($message['type'], $message['text']);
        }
        return $messages;
    }

    /**
     * Generates the markup for login form.
     *
     * @return string
     */
    private function genLogin()
    {
        ob_start(); ?>
        <form name="login" action="./" method="post">
            <fieldset class="uk-fieldset">
                <legend class="uk-legend">[[legend]]</legend>
                <div class="uk-margin">
                    <div class="uk-margin-small-bottom">
                        <div class="uk-inline">
                            <span class="uk-form-icon" uk-icon="icon: user"></span>
                            <input class="uk-input" type="text" name="username" value="[[value_username]]"
                                   placeholder="[[placaholder_username]]">
                        </div>
                    </div>
                    <div class="uk-margin-small-bottom">
                        <div class="uk-inline">
                            <span class="uk-form-icon" uk-icon="icon: lock"></span>
                            <input class="uk-input" type="password" name="password" placeholder="[[placaholder_password]]">
                        </div>
                    </div>
                    <div class="uk-margin-bottom">
                        <input type="hidden" name="action" value="login">
                        <button class="uk-button uk-button-default">[[submit_text]]</button>
                    </div>
                </div>
                <p>[[register_text]] <span uk-icon="icon: link"></span>
                    <a href="../registration/">[[register_link]]</a></p>
            </fieldset>
        </form>
        <?php return ob_get_clean();
    }

    /**
     * Generates the markup for registration form.
     *
     * @return string
     */
    private function genRegistration()
    {
        ob_start(); ?>
        <form name="login" action="./" method="post">
            <fieldset class="uk-fieldset">
                <legend class="uk-legend">[[legend]]</legend>
                <div class="uk-margin">
                    <div class="uk-margin-small-bottom">
                        <div class="uk-inline">
                            <span class="uk-form-icon" uk-icon="icon: user"></span>
                            <input class="uk-input" type="text" name="username" value="[[value_username]]"
                                   placeholder="[[placaholder_username]]">
                        </div>
                    </div>
                    <div class="uk-margin-small-bottom">
                        <div class="uk-inline">
                            <span class="uk-form-icon" uk-icon="icon: mail"></span>
                            <input class="uk-input" type="email" name="email" value="[[value_email]]"
                                   placeholder="[[placaholder_email]]">
                        </div>
                    </div>
                    <div class="uk-margin-small-bottom">
                        <div class="uk-inline">
                            <span class="uk-form-icon" uk-icon="icon: lock"></span>
                            <input class="uk-input" type="password" name="password" placeholder="[[placaholder_password]]">
                        </div>
                    </div>
                    <div class="uk-margin-small-bottom">
                        <div class="uk-inline">
                            <span class="uk-form-icon" uk-icon="icon: lock"></span>
                            <input class="uk-input" type="password" name="confirm" placeholder="[[placaholder_confirm]]">
                        </div>
                    </div>
                    <p>[[terms_and_conditions_text]] <a href="../privacy-policy/">[[terms_and_conditions_link]]</a></p>
                    <div class="uk-margin-bottom">
                        <input type="hidden" name="action" value="registration">
                        <button class="uk-button uk-button-default">[[submit_text]]</button>
                    </div>
                </div>
                <p>[[login_text]] <span uk-icon="icon: link"></span> <a href="../login/">[[login_link]]</a></p>
            </fieldset>
        </form>
        <?php return ob_get_clean();
    }

    /**
     * Private user area
     *
     * @return string
     */
    private function genUser()
    {
        ob_start();

        if($this->processor->currentUser && $this->processor->currentUser->id) : ?>
            <h3>Hello <?php echo $this->processor->currentUser->name; ?>, welcome to your private area.</h3>
            <p>Your user role is <strong><?php echo $this->processor->currentUser->role; ?></strong></p>
            <p><a href="../logout/">Logout</a> <span uk-icon="icon: sign-out"></span></p>
        <?php else: ?>
            <h3>Hello user you are not logged in, restricted access.</h3>
            <p><span uk-icon="icon: sign-in"></span> <a href="../login/">Sign-in</a></p>
        <?php endif;

        return ob_get_clean();
    }

    /**
     * Generates a formatted message depending on the type
     *
     * @param $type
     * @param $text
     *
     * @return string
     */
    private function genMessage($type, $text)
    {
        if($type == 'danger') {
            return '<div uk-alert class="uk-alert-danger">'.$text.'<a class="uk-alert-close" uk-close></a></div>';
        } elseif($type == 'success') {
            return '<div uk-alert class="uk-alert-success">'.$text.'<a class="uk-alert-close" uk-close></a></div>';
        }
    }
}

As you can see, most methods are handling the generation of different site areas like login, registration form or just simply rendering messages. At the top of the file the two public methods renderContent() and renderMessages() called both in user-admin.php template.

This is our Controller.php:

<?php namespace UserAdministrator;
/**
 * Class Controller
 * @package UserAdministrator
 *
 * The Controller has not really a purpose,
 * its job is to handle data that the user submits
 *
 */
class Controller
{
    /**
     * @var object Processor|null
     */
    private $processor = null;

    /**
     * @var object Input|null - User input
     */
    public $input = null;

    /**
     * @var object Sanitizer|null - IM Sanitizer class instance
     */
    private $sanitizer = null;

    /**
     * Controller constructor.
     *
     * @param $processor
     */
    public function __construct($processor) {
        $this->processor = $processor;
        $this->input = new Input();
        $this->sanitizer = $this->processor->imanager->sanitizer;
    }

    /**
     * @param $name
     */
    public function setSection($name) {
        $this->processor->prepareSection($name, $this->input->whitelist);
    }

    /**
     * Lets the unauthorized calls go to waste
     * instead of causing a fatal error.
     *
     * @param $name
     * @param $arguments
     */
    public function __call($name, $arguments)
    {
        if(method_exists($this, $name)) {
            $reflection = new \ReflectionMethod($this, $name);
            if(!$reflection->isPublic()) return;
        }
    }

    /**
     * Login action
     *
     * Login form was sent
     */
    public function login()
    {
        $this->input->whitelist->username = $this->sanitizer->text(
            $this->input->post->username, array('maxLength' => 100)
        );
        $this->input->whitelist->password = $this->input->post->password;

        $this->processor->actionLogin($this->input->whitelist);
    }

    /**
     * Registration action
     *
     * Form is sent
     */
    public function registration()
    {
        $this->input->whitelist->username = $this->sanitizer->pageName(
            $this->input->post->username, array('maxLength' => 100)
        );
        $this->input->whitelist->email = $this->sanitizer->email(
            $this->input->post->email
        );
        $this->input->whitelist->password = $this->input->post->password;
        $this->input->whitelist->confirm = $this->input->post->confirm;

        $this->processor->actionRegistration($this->input->whitelist);
    }

    /**
     * Confirmation action
     *
     * Confirmation link clicked
     */
    public function confirmation()
    {
        $this->input->whitelist->key = rawurldecode($this->input->get->key);

        $this->input->whitelist->user = $this->sanitizer->pageName(
            rawurldecode($this->input->get->user), array('maxLength' => 100)
        );

        $this->processor->actionConfirmation($this->input->whitelist);
    }

}

class Input
{
    public $post;
    public $get;
    public $whitelist;

    public function __construct()
    {
        $this->post = new Post();
        $this->get = new Get();
        $this->whitelist = new Whitelist();
        foreach($_POST as $key => $value) { $this->post->{$key} = $value; }
        foreach($_GET as $key => $value) { $this->get->{$key} = $value; }
    }
}

class Post
{
    /**
     *
     * @param string $key
     * @param mixed $value
     * return $this
     *
     */
    public function __set($key, $value) { $this->{$key} = $value;}
    public function __get($name) { return isset($this->{$name}) ? $this->{$name} : null;}
}

class Get
{
    /**
     *
     * @param string $key
     * @param mixed $value
     * return $this
     *
     */
    public function __set($key, $value) { $this->{$key} = $value; }
    public function __get($name) { return isset($this->{$name}) ? $this->{$name} : null; }
}

class Whitelist
{
    /**
     *
     * @param string $key
     * @param mixed $value
     * return $this
     *
     */
    public function __set($key, $value) { $this->{$key} = $value; }
    public function __get($name) { return isset($this->{$name}) ? $this->{$name} : null; }
}

The main part of our application is the Processor, it is our Model and allow access for the data to be viewed, collected and written to, and is the bridge between the View and the Controller components:

<?php namespace UserAdministrator;
/**
 * Class Processor
 * @package UserAdministrator
 *
 * Processors purpose is to process data into storage or
 * seek and prepare data to be passed along to the other
 * components.
 *
 */
class Processor
{
    /**
     * @var array - Prepared data for the View
     */
    public $data = array();

    /**
     * @var array - Messages to display in View
     */
    public $messages = array();

    /**
     * @var null - Current section
     */
    public $section = null;

    /**
     * @var object ItemManager|null
     */
    public $imanager = null;

    /**
     * @var object ItemMapper|null
     */
    private $itemMapper = null;

    /**
     * @var object Category|null
     */
    private $usersCategory = null;

    /**
     * @var object SimpleItem|null
     */
    public $currentUser = null;

    /**
     * This is a limit on the number of possible new user registrations.
     * We don't want to have our hard drive crammed with an unnecessarily
     * large number of accounts.
     *
     * @var int
     */
    protected $maxUsers = 1000;

    /**
     * Model constructor.
     */
    public function __construct()
    {
        $this->imanager = imanager();

        if(isset($_SESSION['messages'])) {
            $this->messages = $_SESSION['messages'];
            unset($_SESSION['messages']);
        }
        if(isset($_SESSION['user'])) {
            $this->init();
            $this->currentUser = unserialize($_SESSION['user']);
        }
    }

    /**
     * Provides a lazy init method to build the ItemManager's
     * class instancess we intended to use locally.
     */
    private function init()
    {
        $this->usersCategory = $this->imanager->getCategoryMapper()->getCategory('name=Users');
        $this->itemMapper = $this->imanager->getItemMapper();
    }

    /**
     * Tries to execute a method to prepare the data for the View.
     *
     * @param $name
     * @param $whitelist
     */
    public function prepareSection($name, $whitelist)
    {
        $this->section = $this->imanager->sanitizer->pageName($name);

        $method = 'section'.ucfirst($this->section);
        if(method_exists($this, $method)) {
            $this->data = $this->$method($whitelist);
        }
    }

    /**
     * Prepares data for the 'Login' form
     */
    private function sectionLogin($whitelist)
    {
        // If the user is already logged in, redirect him to the user area
        if($this->currentUser && $this->currentUser->id) {
            \Util::redirect('../user/');
            exit;
        }
        return array(
            'legend' => 'Login',
            'value_username' => $whitelist->username,
            'register_text' => 'You are not registered yet,',
            'register_link' => 'create your account',
            'submit_text' => 'Login',
            'placaholder_username' => 'Username or email',
            'placaholder_password' => 'Password',
        );
    }

    /**
     * Prepares data for the 'Registration' form
     */
    private function sectionRegistration($whitelist)
    {
        // If the user is already logged in, redirect him to the user area
        if($this->currentUser && $this->currentUser->id) {
            \Util::redirect('../user/');
            exit;
        }
        return array(
            'legend' => 'Signing up',
            'value_username' => $whitelist->username,
            'placaholder_username' => 'Username',
            'value_email' => $whitelist->email,
            'placaholder_email' => 'Email',
            'login_text' => 'Already registered,',
            'login_link' => 'log in now',
            'submit_text' => 'Sign Up',
            'placaholder_password' => 'Password',
            'placaholder_confirm' => 'Confirm',
            'terms_and_conditions_text' => 'By clicking Sign Up, you agree to our Terms and that you have read our ',
            'terms_and_conditions_link' => 'Data Use Policy'
        );
    }

    /**
     * Here no output is performed, we just directly execute
     * the logout method and redirect the user to the login page.
     */
    private function sectionLogout() { $this->actionLogout(); }

    /**
     * Checks the user input for correctness and completeness
     * and then attempts the login process.
     *
     * @param $whitelist
     */
    public function actionLogin($whitelist)
    {
        if(!$whitelist->username || !$whitelist->password) {
            $this->messages[] = array('type' => 'danger',
                'text' => 'Please fill in all fields!'
            );
            $this->prepareSection('login', $whitelist);
            return;
        }

        // It looks like the data was transmitted correctly, so let's
        // initialize all the required instances.
        $this->init();

        $this->itemMapper->alloc($this->usersCategory->id);
        $item = $this->itemMapper->getSimpleItem('name='.
            $this->imanager->sanitizer->pageName($whitelist->username));
        if(!$item) {
            $item = $this->itemMapper->getSimpleItem('email='.
                $this->imanager->sanitizer->email($whitelist->username));
            if(!$item) {
                $this->messages[] = array('type' => 'danger',
                    'text' => 'The data you entered is not correct!'
                );
                $this->prepareSection('login', $whitelist);
                return;
            }
        }
        // The account is
        if(!$item->active) {
            $this->messages[] = array('type' => 'danger',
                'text' => 'Your account is not activated, all accounts need to be activated '.
                    'by an activation link that arrives via email to the address you provided.'
            );
            $this->prepareSection('login', $whitelist);
            return;
        }

        // Verifies that password matches
        if(password_verify($whitelist->password, $item->password)) {
            $this->currentUser = $item;

            if($this->userLogin()) {
                \Util::redirect('../user/');
                exit;
            }

            $this->messages[] = array('type' => 'danger',
                'text' => 'Error while logging in!'
            );
            return;
        }

        $this->messages[] = array('type' => 'danger',
            'text' => 'The data you entered is not correct!'
        );
        $this->prepareSection('login', $whitelist);
        return;
    }

    /**
     * User will be logged in. Sessions are created.
     *
     * @return bool
     */
    private function userLogin()
    {
        if(!$this->currentUser) return false;

        // Empty password and salt, because it is no longer needed
        unset($this->currentUser->salt);
        unset($this->currentUser->password);

        $_SESSION['user'] = serialize($this->currentUser);
        $_SESSION['messages'][] = array('type' => 'success',
            'text' => 'You have been successfully logged in.'
        );
        return true;
    }

    /**
     * Logs the user out of the system.
     *
     * @return void
     */
    public function actionLogout()
    {
        if(!$this->currentUser) return;

        unset($this->currentUser);
        if(isset($_SESSION['user'])) { unset($_SESSION['user']); }

        $_SESSION['messages'][] = array('type' => 'success',
            'text' => 'You successfully logged out.'
        );

        \Util::redirect('../login/');
        exit;
    }

    /**
     * This method attempts to register a new user in the system
     *
     * @param $whitelist
     */
    public function actionRegistration($whitelist)
    {
        // Don't allow empty fields
        if(!$whitelist->username || !$whitelist->email ||
            !$whitelist->password || !$whitelist->confirm) {
            $this->messages[] = array('type' => 'danger',
                'text' => 'Please fill in all fields!'
            );
            $this->prepareSection('registration', $whitelist);
            return;
        }

        // It looks like the data was transmitted correctly, so let's
        // initialize all the required instances.
        $this->init();

        $this->itemMapper->alloc($this->usersCategory->id);
        $item = $this->itemMapper->getSimpleItem('name='.$whitelist->username);
        // The username already exists
        if($item) {
            $this->messages[] = array('type' => 'danger',
                'text' => 'This username is already assigned!'
            );
            $this->prepareSection('registration', $whitelist);
            return;
        }

        $item = $this->itemMapper->getSimpleItem('email='.$whitelist->email);
        // The email already exists
        if($item) {
            $this->messages[] = array('type' => 'danger',
                'text' => 'This email address is already assigned!'
            );
            $this->prepareSection('registration', $whitelist);
            return;
        }

        // The maximum number of new users has been reached
        if(count($this->itemMapper->simpleItems) >= $this->maxUsers) {
            $this->messages[] = array('type' => 'danger',
                'text' => 'The maximum number of new users has been reached, currently no registration is possible!'
            );
            $this->prepareSection('registration', $whitelist);
            return;
        }

        // Create new user
        $user = new \Item($this->usersCategory->id);

        $user->name = $whitelist->username;
        $user->setFieldValue('email', $whitelist->email);
        // Salt is no longer necessary
        $inputPass = new \InputPassword($user->fields->password);
        $newSalt = $inputPass->randomString();

        $inputPass->salt = $newSalt;
        $inputPass->confirm = $whitelist->confirm;
        $result = $inputPass->prepareInput($whitelist->password);
        if(!$result || is_int($result)) {
            switch($result) {
                case 2:
                    $this->messages[] = array('type' => 'danger',
                        'text' => 'The password should consist of at least '.
                            $user->fields->password->minimum.' characters!'
                    );
                    $this->prepareSection('registration', $whitelist);
                    return;
                case 3:
                    $this->messages[] = array('type' => 'danger',
                        'text' => 'The password should consist of a maximum of '.
                            $user->fields->password->maximum.' characters!'
                    );
                    $this->prepareSection('registration', $whitelist);
                    return;
                case 7:
                    $this->messages[] = array('type' => 'danger',
                        'text' => 'The password is not equal to password confirm in comparison!'
                    );
                    $this->prepareSection('registration', $whitelist);
                    return;
                default:
                    $this->messages[] = array('type' => 'danger',
                        'text' => 'Error setting the password value!'
                    );
                    $this->prepareSection('registration', $whitelist);
                    return;
            }
        }

        $user->fields->password->salt = $result->salt;
        $user->fields->password->value = $result->value;

        // By default all new users are guests
        $user->setFieldValue('role', 'Guest');

        if($user->save() && $this->saveSimpleItem($user)) {

            $recipient = $this->itemMapper->simpleItems[$user->id];

            if(!$this->dropConfirmation($recipient)) {
                $this->messages[] = array('type' => 'danger',
                    'text' => 'Email could not be sent. Check your email configuration!'
                );
                $this->prepareSection('registration', $whitelist);
                return;
            }

            $this->messages[] = array('type' => 'success',
                'text' => 'Thank you for registering on our site. We will send you a '.
                    'confirmation email containing your activation link.'
            );
            return;
        }

        $this->messages[] = array('type' => 'danger',
            'text' => 'Error saving user data!'
        );
        $this->prepareSection('registration', $whitelist);
        return;
    }

    /**
     * The method saves SimpleItem object permanently.
     *
     * @return bool
     */
    protected function saveSimpleItem($curitem)
    {
        $this->itemMapper->simplify($curitem);
        return ($this->itemMapper->save() !== false) ? true : false;
    }

    /**
     * Validates the confirmation data submitted
     * and activates the user account.
     *
     * @param $whitelist
     */
    public function actionConfirmation($whitelist)
    {
        if(!$whitelist->user || !$whitelist->key) {
            $_SESSION['messages'][] = array('type' => 'danger',
                'text' => 'The data is not complete, please contact our support.'
            );
            \Util::redirect('../login/');
            exit;
        }

        $this->init();

        $this->itemMapper->alloc($this->usersCategory->id);
        $item = $this->itemMapper->getSimpleItem('name='.$whitelist->user);

        if(!$item) {
            $_SESSION['messages'][] = array('type' => 'danger',
                'text' => 'This account no longer exists.'
            );
            \Util::redirect('../login/');
            exit;
        }

        // Check the key sent
        if(strcmp($whitelist->key, md5($item->password.$item->salt)) !== 0) {
            $_SESSION['messages'][] = array('type' => 'danger',
                'text' => 'The passed key is invalid, please contact our support.'
            );
            \Util::redirect('../login/');
            exit;
        }

        $user = null;
        $this->itemMapper->limitedInit($item->categoryid, $item->id);
        if(isset($this->itemMapper->items[$item->id])) {
            $user = $this->itemMapper->items[$item->id];
        }

        if($user) {
            $user->active = 1;
            if($user->save() && $this->saveSimpleItem($user)) {
                $_SESSION['messages'][] = array('type' => 'success',
                    'text' => 'Thank you, your account has just been activated. You can log in now.'
                );
                \Util::redirect('../login/');
                exit;
            }
        }

        $_SESSION['messages'][] = array('type' => 'danger',
            'text' => 'Error saving user data!'
        );
        \Util::redirect('../login/');
        exit;
    }

    /**
     * Sends an e-mail confirmation.
     * We don't use extra library for sending our email,
     * we'll simple use mail() function for sending mail.
     *
     * @param $recipient
     *
     * @return bool
     */
    private function dropConfirmation($recipient)
    {
        // Build confirmation link
        $link = IM_SITE_URL.'confirmation/?action=confirmation&key='.
            rawurlencode(md5($recipient->password.$recipient->salt)).'&user='.$recipient->name;

        // Prepare message data and sent the confirmation
        $subject = 'Email Activation Message';
        $email = "Hi $recipient->name, \r\n\r\nthanks for registering at our website.\r\n".
            "To activate your account click the link below!\r\n\r\nActivation Link: $link";

        $from = 'mypage@email.com';
        $reply = 'mypage@email.com';

        // Send the confirmatin email
        $header = "From: $from\r\n" .
            "Reply-To: $reply\r\n" .
            "X-Mailer: PHP/".phpversion();

        if(!mail($recipient->email, $subject, $email, $header)){ return false; }
        return true;
    }
}

The major work is done, now we need a place where we can merge our components. The functions.php file is the right place to build our relationships and we'll use it to trigger our Controller actions, functions.php:

include 'useradmin/Processor.php';
include 'useradmin/Controller.php';
include 'useradmin/View.php';

$processor = new \UserAdministrator\Processor();
$controller = new \UserAdministrator\Controller($processor);
$view = new \UserAdministrator\View($processor);

$controller->setSection(return_page_slug());

if($controller->input->post->action || $controller->input->get->action) {
    ($controller->input->post->action) ? $controller->{$controller->input->post->action}() :
        $controller->{$controller->input->get->action}();
}

Conclusion

We are covered the basics of user administration and have created a very simple application. Of course, it doesn't cover all the features you may need, but it is a good start to build your own custom application based on these methods.

Watch the demonstration

You can also clone the source on GitHub

Autor: Bigin  |  Tags:  FrameworkPHPGetSimpleDevelopmentItemManager