Codeigniter static variables in model - php

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

Related

how to create insert function in model

In controller I am sending data like that :
$data=array[
'table'=>'ci',
'where'=>'',
'val'=>['name'=>$name,
'pass'=>$pass,
'mobile'=>$mobile,
'date'=>$date,
'status'=>$status
]
];
$this->load->model('show_model');
$this->show_model->insert_data($data);
In the model code I have:
<?php
class show_model extends CI_model{
public function insert_data($data){
}
}
?>
I want to create a function to data in ci table what is the method to get the data from the controller and how can i make the funcyion for insert for what i am sending the data.
I think you are trying to perform insert operation but you couldn't figure it out. Lets take it step by step. Codeigniter has a database library which comes with installation. You can load that library in config->autoload.php and provide database credentials in config->database.php. All set!
Once you have loaded database library you can use bunch of database function. E.g
For Insertion
$this->db->insert('table_name',data);
// Your data can be array of the data you want to insert
Let's say you want to send data from your controller to your Model to save it to db you can do something like this
Class Controller_Name extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('your_model');
}
public function index() {
$data=array(
'username' => 'Your Name',
'email' => 'Your Email',
'password' => 'Your Password'
);
// Send it to DB
$this->your_model->save_data($data);
// Show success
echo 'Data Saved';
}
}
Now in your Model you will have the function save data like this
Class Your_model extends CI_Model {
public function __construct(){
parent::__construct();
}
public function save_data($data){
// Assuming the table name is users
$this->db->insert('users',$data);
}
}
You can do a lot of modifications and enhancements, there is a lot of learning ahead but this is a fair start.
Try
public function insert($data) {
if($this->db->insert('table_name', $data)) {
//Success
}
}
Ensure you are connected to your database from database.php in application/config folder
Hope it helps

Can't initialize my plugin function in ZF2 constructor

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();
}
}

CakePHP: How to use a non-default user model for authentication?

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

Static Variable/Methods in PHP using CakePHP

I'm saving the ID of the conected user in a static variable at MainController, but I need to access this variable in others controllers. When I try to get the value from the variable, the result is always the initial value of the variable, even when I have already modified it.
class MainController extends AppController {
//...
public static $loggedClienteId;
//functions
public function loginCliente(){
//code...
self::$loggedClienteId = $cliente['Cliente']['id'];
var_dump(MainController::$loggedClienteId); //returns the correct value.
return $this->redirect(array('controller' => 'clientes', 'action' => 'index'));
}
}
So, in another controller...
include "MainController.php";
class ClientesController extends AppController {
public $helpers = array('Html', 'Form');
public function index() {
var_dump(MainController::$loggedClienteId); //null, althought it already has a value...
$this->set('clientes', $this->Cliente->find('all'));
}
//functions...
}
Why is that happening?
Use $this->Auth->user('id') to get the current logged in user's id.
The reason your code does not work is because once the request for the login action is completed, the script is over. Setting a variable does not persist across requests. You have to save variables in the session for that.
If it's not the logged in user's id you need, what you have to do is use the SessionComponent and use $this->Session->write('key', 'value'); and to read it in another request/controller $this->Session->read('key');.

How bind CWebUser with model User

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');

Categories