How to bind Yii:app()->user to the model User. That there was a connection type: Yii::app()->user->getUser()
For example, I want to get the currently logged in user's email:
Yii::app()->user->getUser()->email;
I readed wiki post:http://www.yiiframework.com/wiki/80/add-information-to-yii-app-user-by-extending-cwebuser-better-version/
MyWbuser.php in components:
class MyWebUser extends CWebUser{
private $_profile = null;
public $loginUrl='/';
public function init(){
parent::init();
if(!$this->getIsGuest()){
$this->_profile = User::model()->findByPk($this->getId());
}
}
public function getProfile(){
return $this->_profile;
}
}
In config.php:
'user' => array(
'class' => 'MyWebUser',
)
Then you can use:
Yii::app()->user->profile->name
Try this add this code to your useridentity authenticate function
$this->setState('email',$this->email);
And use to access that email anywhere as shown
Yii::app()->user->getState('email');
Related
I've been trying to make an extension to add some function to the CMS. As it's a setting for the CMS I've added it to the settings tab. While I can take values and save them I needed an action on the page to synchronise a system and I can't get my action to be called, here is my code.
private static $db = array(
'Path' => 'Varchar(50)',
);
private static $allowed_actions = array (
'update',
);
public function updateCMSFields(FieldList $fields)
{
$fields->addFieldsToTab('Root.Importer', array(
ImporterPathField::create('Path', 'Path')->setDescription('Path to area'),
FormAction::create('update', 'Synchronise')
));
}
public function update() {
SS_Log::add_writer(new SS_LogEmailWriter('test#example.com'), SS_Log::ERR);
}
It doesn't get called. If I need to add the function to the left nav rather than part of the settings I'm ok with that too but I also tried that with even less success. Is it possible to get the action called on button press?
You need to place the $allowed_actions and the update method in an extension for CMSSettingsController. Also you should probably put the FormAction into the CMSActions list.
Here's how I would do this:
SiteConfigExtension.php
class SiteConfigExtension extends DataExtension
{
private static $db = array(
'Path' => 'Varchar(50)',
);
public function updateCMSFields(FieldList $fields)
{
$fields->addFieldsToTab('Root.Importer', array(
ImporterPathField::create('Path', 'Path')->setDescription('Path to area')
));
}
public function updateCMSActions(FieldList $actions)
{
$actions->push(
FormAction::create('update', 'Synchronise')
);
}
}
CMSSettingsControllerExtension.php
class CMSSettingsControllerExtension extends DataExtension
{
private static $allowed_actions = array (
'update',
);
public function update() {
SS_Log::add_writer(new SS_LogEmailWriter('test#example.com'), SS_Log::ERR);
}
}
I am quite new to ZF2 and I am preparing a demo application with simple login and CRUD system. Now for login I have prepared a plugin which consists of some functions that will authenticate users, return the logged in user data, return the logged in status etc. But the problem that I am facing is I can't initialize any variable into the constructor of my controller which will store any return value from the plugin. It's always showing service not found exception.
Please find my plugin code below:
AuthenticationPlugin.php
<?php
namespace Album\Controller\Plugin;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\Session\Container as SessionContainer;
use Zend\View\Model\ViewModel;
use Album\Entity\User;
class AuthenticationPlugin extends AbstractPlugin{
protected $entityManager;
protected $usersession;
public function __construct(){
$this->usersession = new SessionContainer('UserSession');
}
public function dologin($email,$password)
{
$getData = $this->em()->getRepository('Album\Entity\User')->findOneBy(array('email' => $email, 'password' => $password));
if(count($getData)){
$this->usersession->offsetSet('userid', $getData->getId());
return true;
}
else{
return false;
}
}
public function isloggedin(){
$userid = $this->usersession->offsetGet('userid');
if(!empty($userid)){
return true;
}
else{
return false;
}
}
public function logindata(){
$userid = $this->usersession->offsetGet('userid');
$getData = $this->em()->getRepository('Album\Entity\User')->findOneBy(array('id' => $userid));
return $getData;
}
public function logout(){
$this->usersession->offsetUnset('userid');
}
public function em(){
return $this->entityManager = $this->getController()->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
}
?>
In my module.config.php
'controller_plugins' => array(
'invokables' => array(
'AuthPlugin' => 'Album\Controller\Plugin\AuthenticationPlugin',
)
),
Now I am doing this in my controller:
protected $entityManager;
protected $isloggedin;
protected $authentication;
public function __construct(){
$this->authentication = $this->AuthPlugin();
$this->isloggedin = $this->authentication->isloggedin();
}
The error I am getting is like below:
An error occurred An error occurred during execution; please try again
later. Additional information:
Zend\ServiceManager\Exception\ServiceNotFoundException
File:
D:\xampp\htdocs\subhasis\zf2-tutorial\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php:555
Message:
Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for AuthPlugin
But if I write the above constructor code in any of my controller actions everything is fine. in ZF1 I could initialize any variable in the init() method and could use the variable in any of my actions. How can I do this in ZF2? Here, I want to detect if the user is logged in the constructor itself. Now I have to call the plugin in every action which I don't want.
What should I do here?
The error you are receiving is because you are trying to use the ServiceManager (via the Zend\Mvc\Controller\PluginManager) in the __construct method of the controller.
When a controller is registered as an invokable class, the Service Manager (ControllerManager) is responsible for the creating the controller instance. Once created, it will then call the controllers various default 'initializers' which also inlcudes the plugin manager. By having your code in __construct it is trying to use the plugin manager before it has been set.
You can resolve this by using a controller factory, rather than an invokable in module.config.php.
'controllers' => [
'factories' => [
'MyModule\Controller\Foo' => 'MyModule\Controller\FooControllerFactory',
],
],
Then the factory
namespace MyModule\Controller\FooControllerFactory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class FooControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $controllerManager)
{
$serviceManager = $controllerManager->getServiceLocator();
$controllerPluginManager = $serviceManager->get('ControllerPluginManager');
$authPlugin = $controllerPluginManager->get('AuthPlugin');
return new FooController($authPlugin);
}
}
Lastly, update the controller __construct to add the new argument and remove the call to $this->authPlugin()
class FooController extends AbstractActionController
{
public function __construct(AuthPlugin $authentication)
{
$this->authentication = $authentication;
$this->isloggedin = $authentication->isloggedin();
}
}
Hi i have a table name chat_users
I have connected users table for last few projects it working fine. But this is my first project i have a different table name chat_users
I want to login this table with username and password
I have tried but unable to login.
Please help me.
Code-
AppController.php
<?php
App::uses('Controller', 'Controller');
class AppController extends Controller {
public $components = array('Auth', 'Session', 'Email', 'Cookie', 'RequestHandler', 'Custom');
public $helpers = array('Html', 'Form', 'Cache', 'Session','Custom');
function beforeFilter() {
parent::beforeFilter();
$this->Auth->authenticate = array(
'Form' => array (
'scope' => array('ChatUser.is_active' => 1),
'fields' => array('ChatUser.username' => 'username', 'ChatUser.password' => 'password'),
)
);
}
}
?>
UsersController.php
<?php
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public $name = 'Users'; //Controller name
public $uses = array('ChatUser');
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('login');
}
public function index() {
}
public function login() {
$this->layout='login';
if ($this->request->is('post')) {
if (!$this->Auth->login()) {
$this->Session->setFlash(__('Invalid username or password, try again'), 'error_message');
$this->redirect($this->Auth->redirect());
}
}
if ($this->Session->read('Auth.ChatUser')) {
return $this->redirect(array('action' => 'index'));
exit;
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
}
Above query i am getting missing table.
See screenshot-
Your auth component configuration is incorrect. You are missing the appropriate userModel option, which defines the name of the model to use
And the fields configuration doesn't work the way your are using it, the keys must be named username and password, and the value can then contain the actual column name, however since your columns are obviously using the default names, there's no need to use this option at all.
$this->Auth->authenticate = array(
'Form' => array (
'scope' => array('ChatUser.is_active' => 1),
'userModel' => 'ChatUser'
)
);
Also the session key will always be Auth.User unless you are explicitly changing it via AuthComponent::$sessionKey:
$this->Auth->sessionKey = 'Auth.ChatUser';
However, you are better of using the auth component to access the user data anyways:
// Use anywhere
AuthComponent::user('id')
// From inside a controller
$this->Auth->user('id');
See also
Cookbook > Authentication > Configuring Authentication handlers
Cookbook > Authentication > Accessing the logged in user
In two words: I need to get access to the service manager (locator) from external class.
Details:
I have next structure in my ZF2 project:
Api.php is the class, I use in SOAP server, which is created in Controller:
class IncomingInterfaceController extends AbstractActionController
{
...
public function indexAction()
{
if (isset($_GET['wsdl']))
$this->handleWSDL();
else
$this->handleSOAP();
return $this->getResponse();
}
private function handleWSDL()
{
$autodiscover = new AutoDiscover();
$autodiscover->setClass('\Application\Api\Api')->setUri($this->getURI());
$autodiscover->handle();
}
In this Api.php class I need to get access to services.
I need something like this in my Api.php class:
public function OnNewDeal($uid)
{
$error_log=$this->getServiceLocator()->get('error_log'); // this doesn't work!
$error_log->write_error('error_text');
}
In Module.php
public function getServiceConfig() {
return array(
'invokables' => array(
'Application\Api\Api' => 'Application\Api\Api'
)
);
}
In Api.php
class Api implements ServiceLocatorAwareInterface{
protected $services;
public function OnNewDeal($uid){
$this->getServiceLocator()->get('error_log')->write_error('SOAP ERROR');
}
public function setServiceLocator(ServiceLocatorInterface $serviceLocator){
$this->services = $serviceLocator;
}
public function getServiceLocator(){
return $this->services;
}
}
In IncomingInterfaceController.php
class IncomingInterfaceController extends AbstractActionController{
...
protected $api;
public function indexAction()
{
if (isset($_GET['wsdl']))
$this->handleWSDL();
else
$this->handleSOAP();
return $this->getResponse();
}
private function handleWSDL()
{
$autodiscover = new AutoDiscover();
$autodiscover->setClass('\Application\Api\Api')->setUri($this->getURI());
$autodiscover->handle();
}
public getApi(){
if(!$api){
$this->api = $this->getServiceLocator()->get('Application\Api\Api');
}
return $this->api;
}
In controller where you do $this->handleSOAP(); use setObject with already created instance instead setClass.
You should pass into Api __construct $this->getServiceLocator() and handle it there.
class IncomingInterfaceController extends AbstractActionController
{
private function handleSOAP()
{
$soap = new Server(null, array('wsdl'=>$this->getWSDLURI()));
$soapClass = new \Application\Api\Api($this->getServiceLocator());
$soap->setObject($soapClass);
$soap->handle();
}
In Api class, handle serviceManager instance and use as you wish:
class Api
{
protected $serviceManager;
public function __construct($serviceManager)
{
$this->serviceManager = $serviceManager;
}
public function OnNewDeal($uid)
{
$this->serviceManager->get('error_log')->write_error('SOAP ERROR');
}
....
}
Perhaps your API could implement ServiceLocatorAwareInterface like:
class Api implements ServiceLocatorAwareInterface
and add
class Api implements ServiceLocatorAwareInterface
{
protected $serviceManager;
}
Then the service manager would be available
UPDATED
module.config.php example
<?php
return array(
'service_manager' => array(
'factories' => array(
'Api' => 'Namespace\Api'
),
'shared' => array(
'Api' => false
)
),
)
?>
Injecting the Service Manager instance to an user defined "service locator aware class" should responsibility of the framework's itself (via initializers, invokables or user defined factories) not a specific controller's handleSOAP() method.
Yes, #SirJ's solution will work too but that's not a good practice. ZF2 provides ready-to-use Traits and Interfaces exactly for requirements like this. Just use them!
Your very own API class should seem like this:
<?php
namespace Application\Api;
use Zend\ServiceManager\ServiceLocatorInterface;
class Api implements ServiceLocatorInterface
{
// Here is the trait. (php >= 5.4)
use \Zend\ServiceManager\ServiceLocatorAwareTrait;
public function OnNewDeal($uid)
{
$this->getServiceLocator()->get('error_log')->write_error('SOAP ERROR');
}
}
And you should add this key to your module.config.php
<?php
return array(
'service_manager' => array(
'invokables' => array(
'api-service' => 'Application\Api\Api',
)
);
Thats all! Now you can:
<?php
...
$soap = new Server(null, array('wsdl'=>$this->getWSDLURI()));
$soapClass = $this->getServiceLocator()->get('api-service');
$soap->setObject($soapClass);
...
Once a user has logged in- I want all my models to know the user's id. (Even if they are called later on).
I thought about using a static variable but it doesn't seem to work
class Base_model extends CI_Model {
static protected $user_id;
}
class Log_in_model extends Base_model {
public function log_in(){
self::$user_id = 69;
}
}
class A_model extends Base_model {
public function do_A(){
echo self::$user_id;
}
}
class B_model extends Base_model {
public function do_B(){
echo self::$user_id;
}
}
initailize session
$this->load->library('session');
after user logs in,save the userdata in session userdata
$newdata = array(
'username' => 'USERNAME',
'email' => 'EMAIL',
'user_id' => 'USERID',
'logged_in' => TRUE
);
$this->session->set_userdata('userdetails',$newdata); //setting data in session with a name userdetails
get the session userdata..
print_r($this->session->userdata('userdetails')); //get userdetails from session
to destroy userdetails from session use..
$this->session->unset_userdata('userdetails');
if u want to read more about session then read this..
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html