WordPress Role Based Authentication in Yii

You are viewing revision #3 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#2)

This tutorial is for people that are integrating Yii into WordPress. Meaning that WordPress is the host platform, and that Yii will be handling AR, CRUD, etc.

Our User Class

This should be saved in an auto-loaded location, in our application it was application.components, which was included as part of our application.import[].

<?php
class wpUser extends CApplicationComponent implements IWebUser, IApplicationComponent {
        public function init ()
        {
            parent::init();
        }
        function checkAccess ($operation, $params = array()) {
            return current_user_can($operation);
        }
        function getId() {
            return get_current_user_id();
        }
        function getIsGuest () {
            $is_user_logged_in = is_user_logged_in();
            return ! $is_user_logged_in;
        }
        function getName () {
            $name = wp_get_current_user()->user_login;
            return $name;
        }
        public function loginRequired()
        {
            wp_login_form(array('redirect' => Yii::app()->getRequest()->getUrl()));
        }
    }
?>
Setting up the main.php configuration to use our new user class
// application components
	'components'=>array(
		'user'=>array(
			'class' => 'wpUser'
//Make sure you delete the allowAutoLogin option
		)); 
Sample Code inside of our controllers
<?php public function accessRules()
{
    return array(
        array('allow',
            'actions'=>array('index','view'),
            'roles'=>array('publish_posts') 
            //WordPress capability check. 
            //  See @link http://codex.wordpress.org/Roles_and_Capabilities
        ),
 }
 ?>
All done

Voila! You will now be able to specify WordPress capabilities to limit access to certain features, all inside of your main controller class!