How to pass data from model to view(or to controller) - php

The question is simple:
How can i pass data from model to view(or back to the controller) to display errors like "your password is too short"
Here is the controller
class UsersController extends Controller {
private $username;
private $password;
function register()
{
if($_POST)
{
$this->User->username = $_POST['username'];
$this->User->password = $_POST['password'];
$this->User->register();
}
}
}
the model
class User extends Model {
public $username;
public $password;
function register()
{
$username = $this->username;
$password = $this->password;
if (!empty($username) && !empty($password))
{
// registration process
}
else
{
// "you must provide a username and password" or something like that
}
}

Just have your register function in your model return "PASSWORD"; to the controller and have your controller take the return from the model and return it to the view. Let the view interpret what the error output for "PASSWORD" is.
Example:
the controller
class UsersController extends Controller {
private $username;
private $password;
function register()
{
if($_POST)
{
$this->User->username = $_POST['username'];
$this->User->password = $_POST['password'];
return $this->User->register();
}
}
}
the model
class User extends Model {
public $username;
public $password;
function register()
{
$username = $this->username;
$password = $this->password;
if (!empty($username) && !empty($password))
{
// ...
return "SUCCESS";
}
else
{
return "PASSWORD";
}
}
}
the view
$responses = array("SUCCESS" => "Registered Successfully!", "PASSWORD" => "You must provide a username and password!");
$result = $this->UsersController->register();
echo $responses[$result];

Simply have your model methods to return a value, or throw exceptions, like any normal method. Then handle it in the controller. The view shouldn't touch the data directly from the model, that's the controller's job.

public function addAction()
{
$form = $this->_getForm();
$this->view->form = $form;
$this->render('add', null, true);
}
public function editAction()
{
$id = $this->getRequest()->getParam(0);
$Model = DI::get('yourclass_Model');
$form = $this->_getForm();
$data = $Model->getData();
$form->populate($data);
$this->view->flashMessages = $this->_helper->FlashMessenger->getMessages();
$this->view->form = $form;
$this->render('add', null, true);
}
public function saveAction()
{
$form = $this->_getForm();
$Model = DI::get('yourclass_Model');
try{
$saved = $Model->saveForm($form, $_POST);
} catch (Exception $e) {
echo "<pre>";
print_r($e);
exit;
}
if($saved)
{
$this->_helper->FlashMessenger('Record Saved!');
$this->_redirect("edit".$form->id->getValue(), array('exit'=>true));
}
$this->view->errorMessage = 'There were some errors';
$this->view->form = $form;
$this->render('add', null, true);
}

Create a class which implements Singleton pattern and ArrayAccess interface.
Or create something similar with dependency injection.
The ultimate solution would be if you create some validation architecture. (The model validates its self and it's error state is available in the views.)

Related

How can use setstate in Yii

I want create random session after successful sign in and destroy it after log out.
How can do it? I used $this->user->setState
I added this code
class UserIdentity extends CUserIdentity {
protected $_id;
public function authenticate(){
$user = User::model()->find('LOWER(username)=?', array(strtolower($this->username)));
if(($user===null) || ($this->password!==$user->password)) {
$this->errorCode = self::ERROR_USERNAME_INVALID;
} else {
$this->_id = $user->id;
$this->username = $user->username;
$this->user->setState('random',Yii::app()->user->random);
$this->errorCode = self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId(){
return $this->_id;
}
}
Use $this->setState instead of $this->user->setState

PHP OOP - Passing object to function is not working

I have a problem here on PHP OOP. I try to do something that I always do in .NET - pass the whole object to the function. Unfortunately, the script didn't appear to work and when I try to debug (using Netbeans) it stopped here:
$ud = new userdetails($fullname, $email, $contact, $username, $password, $password2);
Can somebody tell me what did I do wrongly? Thanks in advance!
My script:
<?php
include 'class/registration.php';
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$ud = new userdetails($fullname, $email, $contact, $username, $password, $password2);
if (registration::checkEmptyField($ud)==true){
$error = "Please don't leave any field empty";
}
userdetail class:
<?php
class userdetails {
protected $_fullname;
protected $_email;
protected $_contact;
protected $_username;
protected $_password;
protected $_password2;
public function __construct($fullname,$email,$contact,$username,$password,$password2) {
$this->_fullname = $fullname;
$this->_email = $email;
$this->_contact = $contact;
$this->_username = $username;
$this->_password = $password;
$this->_password2 = $password2;
}
public function get_fullname() {
return $this->_fullname;
}
public function get_email() {
return $this->_email;
}
public function get_contact() {
return $this->_contact;
}
public function get_username() {
return $this->_username;
}
public function get_password() {
return $this->_password;
}
public function get_password2() {
return $this->_password2;
}
}
registration class:
<?php
class registration {
function checkEmptyField(&$userdetails){
if ($userdetails-> get_fullname == ''){
return true;
}
elseif ($userdetails->get_email == ''){
return true;
}
elseif ($userdetails->get_contact == ''){
return true;
}
elseif ($userdetails->get_username == ''){
return true;
}
elseif ($userdetails->get_password == ''){
return true;
}
elseif ($userdetails->get_password2 == ''){
return true;
}
}
}
You ask for a property, not a method here: $userdetails-> get_fullname
Correct way: $userdetails-> get_fullname()
You should always turn on the error reporting, because this should have been reported by php.
The way you call registration::checkEmptyField() requires it to be declared as static.
<?php
class registration {
static function checkEmptyField(userdetails $userdetails) {
...
}
}
There is no need to prepend $userdetails with &, in PHP the objects are always passed by reference. It's better to use type hinting: prepend the parameter name ($userdetails) with its expected type (class userdetails in this case).

How can I pass variable between controller functions

This is my first time doing web programming. I want to make one variable that I can use on some functions, I use public $username; and public $password; and use $this->username and $this->password; but it didn't work. This is my code on controller;
public $can_log ;
public function home(){
$this->load->model("model_get");
$data["results"] = $can_log;
$this->load->view("content_home",$data);
}
public function login(){
$this->load->view("site_header");
$this->load->view("content_login");
$this->load->view("site_footer");
}
public function login_validation(){
$this->load->library('form_validation');
$this->load->view("site_header");
$this->load->view("site_nav");
$this->form_validation->set_rules('username','Username','required|trim|callback_validate_credentials');
$this->form_validation->set_rules('password','Password','required|trim');// use md5 if want to encrpyt this
if($this->form_validation->run()){
redirect('site/home');
} else {
$this->load->view('content_login');
}
}
public function validate_credentials(){
$this->load->model('model_get');
$username = $this->input->post('username');//"user";
$password = $this->input->post('password');//"password";
//I tried both but none of those work
$this->can_log = $this->model_get->can_log_in($username, $password);
if($this->can_log){
return true;
} else {
$this->form_validation->set_message('validate_credentials','Incorrect username/password.');
return false;
}
}
I also tried with public $username and public $password but still can't get it
on my model;
public function can_log_in($username, $password){
$query = $this->db->query("SELECT col1, col2 FROM table1 where id_login = '$username' and id_password = '$password'");
if($query->num_rows() > 0) {
$data = $query->result(); // fetches single row: $query->row();
return $data; //fetches single column: $data->col1;
}
}
so how can I get can_log - that contains col1 and col2 - to other function?
Maybe something like this?
public function with_parameter($parameter)
{
do something with $parameter
}
And then call the function
with_parameter($can_log);
I didn't understood the exact requirements, but try below code if it works for you.
Have followed some CI guidelines which you need to learn.
Controller:
class Controller_name extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model("model_get"); // load models in constructor
$this->can_log = "some value"; // is the way to define a variable
}
public function home()
{
$data["results"] = $this->can_log; // is the way to retrieve value
$this->load->view("content_home",$data);
}
public function validate_credentials()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$is_valid = $this->model_get->can_log_in($username, $password);
if($is_valid)
{
return true;
}
else
{
$this->form_validation->set_message('validate_credentials','Incorrect username/password.');
return false;
}
}
}
Model:
class Model_get extends CI_Model
{
public function can_log_in($username, $password)
{
$where_aray = array("id_login" => $username, "id_password" => $password);
$query = $this->db->get_where("table", $where_array);
if($query->num_rows() > 0)
return $query->row();
return false;
}
}

Function won't pass variable to view

Right now $renderData['username'] won't pass through to the view.
class HomeController extends MY_Controller {
public function index($renderData=""){
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$renderData['username'] = $session_data['username'];
//$this->load->view('pages/home_view', $renderData);
$this->_render('pages/home',$renderData);
}
else
{
//If no session, redirect to login page
redirect('LoginController', 'refresh');
}
}
}
The error I get is...
Which alludes to this code...
<h1>Home</h1>
<h2>Welcome <?php echo $username; ?>!</h2>
Logout
Here is my My_Controller where the _render function is located...
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller{
//Page info
protected $data = Array();
protected $pageName = FALSE;
protected $template = "main";
protected $hasNav = TRUE;
//Page contents
protected $javascript = array();
protected $css = array();
protected $fonts = array();
//Page Meta
protected $title = FALSE;
protected $description = FALSE;
protected $keywords = FALSE;
protected $author = FALSE;
function __construct()
{
parent::__construct();
$this->data["uri_segment_1"] = $this->uri->segment(1);
$this->data["uri_segment_2"] = $this->uri->segment(2);
$this->title = $this->config->item('site_title');
$this->description = $this->config->item('site_description');
$this->keywords = $this->config->item('site_keywords');
$this->author = $this->config->item('site_author');
$this->pageName = strToLower(get_class($this));
}
protected function _render($view,$renderData="FULLPAGE") {
switch ($renderData) {
case "AJAX" :
$this->load->view($view,$this->data);
break;
case "JSON" :
echo json_encode($this->data);
break;
case "FULLPAGE" :
default :
//static
$toTpl["javascript"] = $this->javascript;
$toTpl["css"] = $this->css;
$toTpl["fonts"] = $this->fonts;
//meta
$toTpl["title"] = $this->title;
$toTpl["description"] = $this->description;
$toTpl["keywords"] = $this->keywords;
$toTpl["author"] = $this->author;
//data
$toBody["content_body"] = $this->load->view($view,array_merge($this->data,$toTpl),true);
//nav menu
if($this->hasNav){
$this->load->helper("nav");
$toMenu["pageName"] = $this->pageName;
$toHeader["nav"] = $this->load->view("template/nav",$toMenu,true);
}
$toHeader["basejs"] = $this->load->view("template/basejs",$this->data,true);
$toBody["header"] = $this->load->view("template/header",$toHeader,true);
$toBody["footer"] = $this->load->view("template/footer",'',true);
$toTpl["body"] = $this->load->view("template/".$this->template,$toBody,true);
//render view
$this->load->view("template/skeleton",$toTpl);
break;
}
}
}
Here is an additional function that may be helpful...
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
}
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('pages/login_view');
}
else
{
//Go to private area
// redirect('home', 'refresh');
redirect('HomeController', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
}
?>
What am I doing wrong that is preventing the username to be passed to the view?
PS - let me know any additional documentation I can provide.
something like this
protected function _render($view,data, $renderData="FULLPAGE") {
$this->data = $data;
switch ($renderData) {
case "AJAX" :
$this->load->view($view,$this->data);
break;
case "JSON"

My CI model class with static method is failing

OK...first I read this article..
http://net.tutsplus.com/tutorials/php/6-codeigniter-hacks-for-the-masters/
In the first hack, it says if I include these in my config.php file:
function __autoload($class) {
if (file_exists(APPPATH."models/".strtolower($class).EXT)) {
include_once(APPPATH."models/".strtolower($class).EXT);
}
}
I don't need to extend my model class to CI_Model.
Then the I tried to use $this->db->select('email')->from('users')->where('email', $email); in my model class..CodeIgniter tells me "db" property is not found. Has anyone tried this hack before and know how to get it to work?
class User {
public $id;
public $email;
public $displayName;
public $password;
public static function search_by_email($email) {
$user = new User;
$user->db->select('email')->from('users')->where('email', $email);
$query = $user->db->get();
if ($query->num_rows()==0) {
return false;
}else {
foreach ($query->result() as $key => $val) {
$user->email = $val['email'];
$user->displayName = $val['displayName'];
return $user;
}
}
return null;
}
When I call the static function in my controller I use:
$user = User::search_by_email("xxx#gmail.com");
If I don't extend User, it will show a CI warning: Message: Undefined property: User::$db. If I use User extends CI_Model {}, the server will crash.
Does anyone have an idea about this situation?
Edited:
Then I dumped the silly Nettus' tutorial code, thanks to you guys...but my model is still not working:
class User extends CI_Model {
public $id;
public $email;
public $displayName;
public $password;
public function search_by_email($email) {
$user = new User();
$this->db->select('email')->from('users')->where('email', $email);
$query = $this->db->get();
if ($query->num_rows()==0) {
return false;
}else {
foreach ($query->result() as $key => $val) {
$user->email = $val['email'];
$user->displayName = $val['displayName'];
return $user;
}
}
return null;
}
In my controller I use:
$this->load->model('User');
$user = $this->User->search_by_email("leo.niecn#gmail.com");
My server still crashed.....am I forbidden to write class variables like public $id in my model?
This part of code doesn't make any sense:
function __autoload($class) {
if (file_exists(APPPATH . "models/" . strtolower($class).EXT)) {
include_once(APPPATH . "models/" . strtolower($class).EXT);
}
}
as long as you can load your model from autoload.php under config folder or just do the following when you need the model:
$this->load->model('model_name');
then just call your function.

Categories