How to retrieve array variables in a class - php

I'm new to OOP and very confused about it. A class that collected user info from database based on the ID passed though:
class user {
public $profile_data;
public function __construct($profile_user_id) {
$this->profile_data = user_data($profile_user_id, 'id', 'username', 'password', 'email', 'admin');
}
}
$profile_data[] = new user(1);
How do I get all the variables in the array? How do I echo out the username for example?

Simply try this.
class user {
public $profile_data;
public function __construct($profile_user_id) {
$this->profile_data = user_data($profile_user_id, 'id', 'username', 'password', 'email', 'admin');
}
}
$userObj = new user(1);
$profileData = $userObj->profile_data;
echo $profileData['username'];

Assuming your user_data function is returning an associative array of data, you should be able to access the fields using as such:
$profile = new user(1);
echo $profile->profile_data['username'];
As in Lighthart's example, it would be good practice to create private variables, with functions to access them.
Another option would be to implement the ArrayAccess interface (http://php.net/manual/en/class.arrayaccess.php) Using this interface, you would be able to use your object similarly to how you use an array. That is, you could use:
echo $user['username'];
As a starting point, you could try something like:
class user implements ArrayAccess {
private $data;
public function __construct($profile_user_id) {
$this->data= user_data($profile_user_id, 'id', 'username', 'password', 'email', 'admin');
}
public function offsetSet($offset, $value) {
// Do nothing, assuming non mutable data - or throw an exception if you want
}
public function offsetExists($offset) {
return isset($this->data[$offset]);
}
public function offsetUnset($offset) {
// Do nothing, assuming non mutable data - or throw an exception if you want
}
public function offsetGet($offset) {
return isset($this->data[$offset]) ? $this->data[$offset] : null;
}
}

The example you have given probably won't work for what you are trying to accomplish. It is not clear what function userdata does. Revised:
class User {
private $id;
private $username;
private $password;
private $email;
private $admin;
public function __construct($id, $username, $password, $email, $admin) {
$profileData = user_data($profile_user_id
,'id'
,'username'
,'password'
,'email'
,'admin');
$this->id = $profileData ['id'];
$this->username = $profileData ['username'];
$this->password = $profileData ['password'];
$this->email = $profileData ['email'];
$this->admin = $profileData ['admin'];
}
public function getId(){ return $this->id; }
public function getUsername(){ return $this->username; }
public function getEmail(){ return $this->email; }
public function getAdmin(){ return $this->admin; }
public function setAdmin($admin){ $this->admin = $admin; }
}
The variables are set private. Only the user object should have access to the data directly. However, other objects might want to retrieve the data, which is why there are 4 public get functions. getPassword was omitted because you probably don't want that one publicly available. Also, it is concievable you might set a new admin, so a public setter function was added as well. you would instance the new user (that is, take the class and make a real example of it) thusly:
$user1 = new User(1);
And during usage you would echo these variables by:
echo $user1->getUsername();
Please accept my apologies for not directly answering your question, but that example is headed for trouble.

Related

Codeigniter cannot redeclare class

Not: Its work just one time in loop. Its return this error for other time.
I have a usermodel.php in models. When i use it like
$this->load->model("Usermodel");
$user = $this->Usermodel->quer(1);
it throw "Message: Undefined property: CI_Loader::$Usermodel"
When i use
$this->load->model("Usermodel");
$user = new Usermodel();
it throw "Message: Cannot redeclare class Users"
user class has construct and desturct functions. I call it in Usermodel.php file. And usermodel has construct and destruct functions.
<?php
class User {
public function __construct(){
parent::__construct();
}
private $id;
private $email;
private $name;
private $profilPic;
private $topPic;
private $gender;
private $birthday;
private function setid($id){
$this->id = $id;
}
private function getid(){
return $this->id;
}
private function setemail($email){
$this->email = $email;
}
private function getemail(){
return $this->email;
}
private function setname($name){
$this->name = $name;
}
private function getname(){
return $this->name;
}
private function setprofilPic($profilPic){
$this->profilPic = $profilPic;
}
private function getprofilPic(){
return $this->profilPic;
}
private function settopPic($topPic){
$this->topPic = $topPic;
}
private function gettopPic(){
return $this->topPic;
}
private function setgender($gender){
$this->gender = $gender;
}
private function getgender(){
return $this->gender;
}
private function setbirthday($birthday){
$this->birthday= $birthday;
}
private function getbirhday(){
return $this->birthday;
}
public function __set($name, $value){
$functionname = 'set'.$name;
return $this->$functionname($value);
}
public function __get($name){
$functionname = 'get'.$name;
return $this->$functionname();
}
public function __destruct(){}
}
?>
This is usermodel
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Usermodel extends CI_Model {
public function __construct(){
parent::__construct();
$this->load->view("Users.php");
$this->load->model("Dbmodel");
}
public function quer($id){
$uqcont = array("id" => $id);
$uiqcont = array("userID", $id);
$uq = $this->Dbmodel->control("user", $uqcont);
$uiq = $this->Dbmodel->control("userinfo", $uiqcont, $limit=1, 'userID');
$user = new Users();
if($uq->num_rows()==1){
$uq = $uq->result();
$user->id=$id;
$user->name=$uq[0]->name;
$user->email=$uq[0]->email;
$user->profilPic="girlprofil.png";
$user->topPic="arka.jpg";
}
if($uiq->num_rows()==1){
$uiq=$uiq->result();
if($uiq[0]->profilPic){
$user->profilPic = $uiq[0]->profilPic;
}
if($uiq[0]->topPic){
$user->topPic = $uiq[0]->topPic;
}
}
return $user;
}
public function __destruct(){}
}
?>
This is a part of my view.php
foreach($query->result() as $row){
$cont = array("id" => $row->userID);
$query = $this->Dbmodel->control("user", $cont);
$this->load->model("Usermodel");
$user = new Usermodel();
$user = $user->quer($row->userID);
$date = new datetime($row->date);
$date = $date->format("d.m.Y H:i:s");
//$query = $query->result();
//foreach($query as $qur){
echo '$user->name.'<br>'.$row->comment;
//}
//unset($user);
}
Please look to my error and help me to solve it.
the class User is being declared more than once, probably in the loop you were referring to.
is this line in the loop?
$this->load->model("Usermodel");
if so try moving it out of the loop.
The error is due to loading the model several times in the foreach loop. Load it only once then create instances of the class as many times as you wish
$this->load->model("usermodel");
foreach($query->result() as $row){
$cont = array("id" => $row->userID);
$query = $this->Dbmodel->control("user", $cont);
$user = new Usermodel();
$user = $user->quer($row->userID);
$date = new datetime($row->date);
$date = $date->format("d.m.Y H:i:s");
}
Then consider using small caps in your load->model().
I advise loading the data in the controller then passing the data to the view. Let the controller have most of the logic.For example in the controller
$this->load->model('usermodel');
$data['users'] = $this->usermodel->quer($id)->result();
$this->load->view('users_view', $data);
In the view its as simple as
foreach ($users as $user)
{
//logic e.g. echo $user->name;
}
$this->load->model("X") is doing something like following;
Check models directory if X.php exists and if it exists
it creates the class with the given name in our case "X", [ $this->X = new X(); ]
you can also pass the alternative name to the load->model method like
$this->load->model("X","my_x_model"), in that case the loader module will create
$this->my_x_model = new X();
It was just to give some information about "what happens when you trying to load a model"
You're getting an Undefined property because
$this->load->model("usermodel");
has to be in lowercase.
https://www.codeigniter.com/userguide3/general/models.html#loading-a-model
I change this "class Users" to "class users extends CI_Model" and i move "$this->load->model("usermodel") on over of loop. Then the problem is solved. Thank you for help.

PHP class return nothing

I'm just beginner with PHP OOP. I have a class and output is empty:
$test = new form('name1', 'passw2');
$test->getName();
and class:
<?php
class form
{
protected $username;
protected $password;
protected $errors = array();
function _construct($username, $password){
$this->username=$username;
$this->password=$password;
}
public function getsomething() {
echo '<br>working'. $this->getn() . '<-missed';
}
public function getName(){
return $this->getsomething();
}
public function getn() {
return $this->username;
}
}
?>
And output is only text without username:
POST working
working<-missed
Where is name1?
I've modifed your code a bit and added some examples to play around with.
This should get you started.
class form
{
protected $username;
protected $password;
protected $errors = array();
// construct is a magic function, two underscores are needed here
function __construct($username, $password){
$this->username = $username;
$this->password = $password;
}
// functions starting with get are called Getters
// they are accessor functions for the class property of the same name
public function getPassword(){
return $this->password;
}
public function getUserName() {
return $this->username;
}
public function render() {
echo '<br>working:';
echo '<br>Name: ' . $this->username; // using properties directly
echo '<br>Password:' . $this->password; // not the getters
}
}
$test = new form('name1', 'passw2');
// output via property access
echo $test->username;
echo $test->password;
// output via getter methods
echo $test->getUserName();
echo $test->getPassword();
// output via the render function of the class
$test->render();
Hi You have used _construct it should be __contrust(2 underscores)

Writing a model for a user (php)

I have a users model that has a lot of properties such as first_name, last_name, email, address, address2...etc
I am writing a php class to manage these properties, but it seems like I am writing a lot of the same code. (Getters and setters). Should I use magic methods to manage this? It seems like an OK idea, but I don't want incorrect properties being set. Any ideas?
<?php
class User
{
private $username;
private $email
private $first_name;
private $last_name;
private $address;
private $address2;
function __construct()
{
}
function getUsername()
{
return $this->username
}
function setUsername($username)
{
$this->username = $username;
}
...
}
?>
Unless you are doing validation on the input, there's no point using getters/setters here in my opinion.
Make the properties public, and override the getters/setters for invalid properties using magic methods:
class User
{
public $username;
public $email;
public $first_name;
public $last_name;
public $address;
public $address2;
public function __get($var) {
throw new Exception("Invalid property $var");
}
public function __set($var, $value) {
$this->__get($var);
}
}
$user = new User;
$user->username = 'foo'; // works
$user->foo = 'bar'; // errors
First of all, can't you use public properties?
If no and your properties does not require any logic when getting/setting, i would use __get and __set.
If you really don't want "incorrect" properties being set (why?), a option could be to use a whitelist of properties that's okay to set:
function __set($key, $value) {
$whitelist = array("firstname", "lastname", ..);
if(!in_array($key, $whitelist))
throw new Exception("Invalid property");
}

What is the structure of a (Data Access) Service Class

I learnt that I should be using service classes to persist entities into the database instead of putting such logic in models/controllers. I currently made my service class something like
class Application_DAO_User {
protected $user;
public function __construct(User $user) {
$this->user = $user
}
public function edit($name, ...) {
$this->user->name = $name;
...
$this->em->flush();
}
}
I wonder if this should be the structure of a service class? where a service object represents a entity/model? Or maybe I should pass a User object everytime I want to do a edit like
public static function edit($user, $name) {
$user->name = $name;
$this->em->flush();
}
I am using Doctrine 2 & Zend Framework, but it shouldn't matter
I think you should first consider what you'd like to do with the user objects. For example if you only want to create, update and delete user records (CRUD) I can imagine this type of API:
<?php
public function create (array $data = null)
{
$user = new User($data);
$this->_persist($user)
->_flush();
return $user;
}
public function update (User $user, array $data)
{
foreach ($data as $name => $value) {
$user->$name = $value;
}
$this->_flush();
return $user;
}
public function delete (User $user)
{
$this->_remove($user)
->_flush();
}
I seperated the methods to the entity manager, you can create something like below or skip the seperated methods at all. With these methods you could do additional checkups (for example if you want to persist there can be a check to look if the object is already persisted).
protected function _persist ($obj)
{
$this->_em->persist($obj);
return $this;
}
protected function _detach ($obj)
{
$this->_em->detach($obj);
return $this;
}
protected function _remove ($obj)
{
$this->_em->remove($obj);
return $this;
}
protected function _flush ()
{
$this->_em->flush();
return $this;
}

PHP OOP Design for simple Models

i've a little problem with the proper design for some simple database models. Lets say i have an User Object with getter/setters and an read method. Read querys the database and sets the properties.
class User extends MyDbBaseClass
{
protected $_id;
protected $_name;
public function setId($id)
{
$this->_id = $id;
}
public function setName($name)
{
$this->_name = $name;
}
public function getId()
{
return (int) $this->_id;
}
public function getName()
{
return (string) $this->_name;
}
public function read($id)
{
// fetch ONE record from Database
$this->_id = $this->setId($sqlResult['id');
$this->_name = $this->setName($sqlResult['name']);
}
public function save()
{
// do some sql stuff to save user to database
}
}
My Problem is, how to return multiple users?
public function getCollection()
{
// fetch all user records from database
forearch ($sqlResult as $result) {
// ... no idea..
}
}
Goal:
// works
$u = new User();
$u->read(1);
echo $u->getName();
// dont know the best way
$u = new User();
$uC = $u->getCollection();
foreach ($uC as $u)
{
echo $u->getName();
}
Any best practices for this?
You could just return an array with users
public function getCollection()
{
// fetch all user records from database
$users = array();
forearch ($sqlResult as $result) {
// ... no idea..
$user = new User();
$user->_name = $result->name; // just an example
$user[] = $users;
}
return $users;
}

Categories