PHP api rest router issue - php

To test my android application in a more concrete way, and since my company has no API yet, I decided to "create" it in a simplified way for testing purpose (and learning, i'm only an intern).
The Android app uses Retrofit.
Anyway, I followed one tutorial for a "login" method, where I use the "Post" method in android, passing login and password as #field datas, and everything worked fine, I could retrieve the data in my android app and log in (I do not manage security yet, this will be added later when they hire a devOp)
The problem is after that I wanted to create a Router for more complicated urls (like "/model/client/:id/contracts") and now nothing work anymore. I do not use framework, only composer. I end my internship in two days I do not really have time to learn a big thing.
So, here are the classes that were working before I make the router :
/src/Model/client/login.php :
<?php
namespace App\Model\client;
// required headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: access');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: application/json');
// include database and object files
include_once 'src/config/Database.php';
include_once 'src/Model/client/client.php';
// Instantiate database and connect
$database = new Database();
$db = $database->connect();
// prepare product object
$client = new Client($db);
console.log("Login launched");
// set ID property of record to read
$client->login = isset($_POST['login']) ? $_POST['login'] : die();
$client->password = isset($_POST['password']) ? $_POST['password'] : die();
// read the details of product to be edited
$result = $client->readOne();
$num = $result->rowCount();
//Check if corresponding client
if($num>0){
if($client->city==3){
$client->city = "Valenciennes";
}
$row = $result->fetch(PDO::FETCH_ASSOC);
if($row['city']==3){
$city = "Valenciennes";
} else {$city='randomname';}
$client->id = $row['id'];
$client->login = $row['login'];
$client->raison = $row['raison'];
$client->addr1 = $row['addr1'];
$client->addr2 = $row['addr2'];
$client->city = $city;
$client->telephone = $row['telephone'];
$client->portable = $row['portable'];
$client->fax = $row['fax'];
$client->email = $row['email'];
$client->tva_intra = $row['tva_intra'];
$client->siret = $row['siret'];
$client->gtr = $row['gtr'];
$client->password = $row['password'];
// create array
$logged_client = array(
'id' => $client->id,
'login'=> $client->login,
'raison' => $client->raison,
'addr1' => $client->addr1,
'addr2' => $client->addr2,
'city' => $client->city,
'telephone'=>$client->telephone,
'portable'=>$client->portable,
'fax'=>$client->fax,
'email'=>$client->email,
'tva_intra'=>$client->tva_intra,
'siret'=>$client->siret,
'password'=>$client->password);
// set response code - 200 OK
http_response_code(200);
// make it json format
echo json_encode($logged_client);
}
else {
// set response code - 404 Not found
http_response_code(404);
// tell the user product does not exist
echo json_encode(array("message" => "Client does not exist.".$client->login));
}
?>
The class of the object I need to retrieve (src/Model/client/client):
<?php
class Client{
//db stuff
private $cnx;
private $table_name='client';
//client properties
public $id;
public $login;
public $nom;
public $raison;
public $addr1;
public $addr2;
public $city;
public $telephone;
public $portable;
public $fax;
public $email;
public $tva_intra;
public $siret;
public $gtr;
public $password;
//constructor
public function __construct($db){
$this->cnx = $db;
}
//GetOne ###########################################################################
function readOne(){
$query = 'SELECT * FROM '.$this->table_name.' WHERE login = ? AND password = ?';
// prepare query statement
$stmt = $this->cnx->prepare($query);
// bind id of product to be updated
$stmt->bindParam(1, $this->login);
$stmt->bindParam(2, $this->password);
// execute query
$stmt->execute();
// get retrieved row
return $stmt;
}
}
?>
The database exists, here is the connection and it worked fine :
<?php
class Database {
//DB Params
private $host='localhost';
private $db_name='techcrea';
private $username = 'root';
private $pwd = '';
private $cnx;
//DB Connect
public function connect(){
$this->cnx = null;
try {
$this->cnx = new PDO('mysql:host='.$this->host.';dbname='. $this->db_name, $this->username,$this->pwd);
$this->cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'Connection Error:'.$e->getMessage();
}
return $this->cnx;
}
}
So here are the problems starting : this are the classes I added and now nothing works anymore, I get router exception errors (no matching routes) etc..., not only in my android app that returns an "onfailure" response, but also when i try the url in my navigator :
1 - Index :
<?php
require 'vendor/autoload.php';
$router= new App\Router\Router($_GET['url']);
$router->get('/', function(){
echo "homepage";
});
$router->post('/Model/client/login', function(){
//require_once 'src/Model/client/login.php';
});
$router->get('/Model/client/:id/contrats', function($id){
echo "contrats";
});
$router->run();
2 - Router
<?php
namespace App\Router;
class Router {
private $url;
private $routes =[];
private $namedRoutes= [];
public function __construct($url){
$this->url = $url;
}
public function get($path, $callable, $name =null){
return $this->add($path,$callable,$name,'GET');
}
public function post($path, $callable, $name=null){
return $this->add($path,$callable,$name,'POST');
}
public function patch($path, $callable, $name=null){
return $this->add($path,$callable,$name,'PATCH');
}
public function put($path, $callable, $name=null){
return $this->add($path,$callable,$name,'PUT');
}
public function delete($path, $callable, $name=null){
return $this->add($path,$callable,$name,'DELETE');
}
private function add($path, $callable,$name,$method){
$route = new Route($path, $callable);
$this->routes[$method][]= $route;
if($name){
$this->namedRoutes[$name] = $route;
}
return $route;
}
public function url($name,$params = []){
if(!isset($this->namedRoutes[$name])){
throw new RouterException("no match name route");
}
$this->namedRoutes[$name]->getUrl($params);
}
public function run(){
if(!isset($this->routes[$_SERVER['REQUEST_METHOD']])){
throw new RouterException('request method does not exist');
}
foreach($this->routes[$_SERVER['REQUEST_METHOD']] as $route){
if($route->match($this->url)){
return $route->call();
}
}
throw new RouterException('no matching routes');
}
}
3 - Route
namespace App\Router;
class Route {
private $path;
private $callable;
private $matches = [];
private $params = [];
public function __construct($path, $callable){
$this->path = trim($path,'/');
$this->callable = $callable;
}
public function with($param, $regex){
$this->params[$param] = str_replace('(','(?:', $regex);
return $this;
}
public function match($url){
$url=trim($url, '/');
$path = preg_replace_callback('#:([\w]+)#', [$this, 'paramMatch'], $this->path);
$regex = "#^$path$#i";
if(!preg_match($regex, $url, $matches)){
return false;
}
array_shift($matches);
$this->matches= $matches;
return true;
}
public function call(){
if(is_string($this->callable)){
$params = explode('#', $this->callable);
$controller = "App\\Controller\\".$params[0]."Controller";
$controller = new $controller();
$action = $params[1];
return $controller->$action();
} else {
return call_user_func_array($this->callable, $this->matches);
}}
private function paramMatch($match){
if(isset($this->params[$match[1]])){
return '('.$this->params[$match[1]].')';
}
return '([^/]+)';
}
public function getUrl($params){
$path = $this->path;
foreach($params as $k=>$v){
$path= str_replace(":$k",$v, $path);
}
return $path;
}
}
and the htaccess doc :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
Thank you very much if you help me

Related

session store only one item in array

I'm a new in php, I have a sign up form and I want to store users registered in an array or JSON,
I built user class and when I register a new user I want to add it into this array or JSON, but session array accept only one user in it and when I adding new user session removing the old one and store the new one!
This is my code:
class User
{
private $id;
private $first_name;
private $last_name;
private $email;
private $password;
public function register($id, $firstName, $lastName, $email, $password)
{
$this->id = $id;
$this->first_name = stripslashes($firstName);
$this->last_name = stripslashes($lastName);
$this->email = $email;
$this->password = password_hash($password, PASSWORD_DEFAULT);
}
}
class DB
{
public $users;
public function __construct()
{
$this->users = [];
}
}
<?php
$counter = 0;
$_SESSION['usersDB'] = new DB;
if (isset($_POST['submit'])) {
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$user = new User;
$user->register(++$counter, $firstName, $lastName, $email, $password);
array_push($_SESSION['usersDB']->users, $user);
}
echo '<pre>';
var_dump($_SESSION['usersDB']);
echo '</pre>';
?>
What I should do to sole this and store all users in one place?
You're replacing the session variable with new DB each time you run the script. You shouldn't do that if the session variable is already set.
if (!isset($_SESSION['userdDB'])) {
$_SESSION['usersDB'] = new DB;
}
Also, $counter will always be 1, since you're setting $counter = 0; at the beginning of the script. You could save this in a session variable, but there isn't really a need. You can just use:
$counter = count($_SESSION['usersDB']->users);
I'm not really sure this will do what you really want. Every browser session has its own session variables, so each user will just have a list of users that they have registered. Session variables are also temporary, so it's not a good way to keep a permanent list of registered users.
The right way to keep a permanent list of users is in a database on the server.
using cookies with serialize and unserialize function
user.php
<?php
class User
{
public static $cnt = 0;
private $id;
private $name;
public function __construct($name='')
{
self::$cnt++;
$this->id = self::$cnt;
$this->name = stripslashes($name);
}
public function __get($name){
return $this->$name;
}
public function __set($name,$val){
$this->$name = stripslashes($val);
}
public function __toString(){
return 'user('.$this->id.", ".$this->name.")";
}
}
?>
db.php
<?php
class DB
{
public $users = [];
public function __construct()
{
$this->users = [];
}
public function __toString()
{
$str = "<ul>";
foreach ($this->users as $user)
$str .="<li>".$user."</li>";
$str .= "</ul>";
return $str;
}
}
?>
index.php
<?php
require_once('user.php');
$user1 = new User('Steve');
$user2 = new User('Everst');
require_once('db.php');
$databse = new DB();
$databse->users[] = $user1;
$databse->users[] = $user2;
setcookie('users', serialize($databse),time() + 3600,"/","",0);
echo $_COOKIE['users'];
?>
users.php
<?php
require_once('db.php');
require_once('user.php');
$databse = unserialize($_COOKIE['users']);
echo $databse;
?>
using session with JSON
implements the interface JsonSerializable
override the method jsonSerialize
user.php
<?php
class User implements JsonSerializable
{
public static $cnt = 0;
private $id;
private $name;
public function __construct($name='')
{
self::$cnt++;
$this->id = self::$cnt;
$this->name = stripslashes($name);
}
public function __get($name){
return $this->$name;
}
public function __set($name,$val){
$this->$name = stripslashes($val);
}
public function __toString(){
return 'user('.$this->id.", ".$this->name.")";
}
public function jsonSerialize() {
return array(
'id' => $this->id,
'name' => $this->name
);
}
}
?>
index.php
<?php
session_start();
include('user.php');
include('db.php');
$user1 = new User('Steve');
$user2 = new User('Everst');
$databse = new DB();
$databse->users[] = $user1;
$databse->users[] = $user2;
$_SESSION['database'] = JSON_encode($databse);//{"users":[{"id":1,"name":"Steve"},{"id":2,"name":"Everst"}]}
?>
users.php
<?php
session_start();
$databse = json_decode($_SESSION['database']);
foreach ($databse->users as $user)
echo $user->id." - ".$user->name."<BR>";
?>

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.

Can't retrieve data in PHP API

I'm building a simple CRUD app as a learning exercise in Angularjs and PHP. I have a shell page, mysql backend, a PHP API that handles the SQL requests, and I'm using Angularjs to handle the flow of data between the shell page and the API. I'm working off an API modeled here:
http://angularcode.com/demo-of-a-simple-crud-restful-php-service-used-with-angularjs-and-mysql/
I've tested every component of this app so far and everything works cleanly except the API. All I've done to modify the original was change the syntax to PDO and I adjusted the response function because the existing one didn't work.
The abstract class:
<?php
class REST {
public $_allow = array();
public $_content_type = "application/json";
public $_request = array();
private $_method = "";
private $_code = 200;
public function __construct(){
$this->inputs();
}
public function get_referer(){
return $_SERVER['HTTP_REFERER'];
}
/*public function response($data,$status){
$this->_code = ($status)?$status:200;
$this->set_headers();
echo $data;
exit;
}*/
public function response($status, $status_message, $data){
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['status_message'] = $status_message;
$response['data'] = $data;
$json_response = json_encode($response);
}
private function get_status_message(){
$status = array(
200 => 'OK',
201 => 'Created',
204 => 'No Content',
404 => 'Not Found',
406 => 'Not Acceptable');
return ($status[$this->_code])?$status[$this->_code]:$status[500];
}
public function get_request_method(){
return $_SERVER['REQUEST_METHOD'];
}
private function inputs(){
switch($this->get_request_method()){
case "POST":
$this->_request = $this->cleanInputs($_POST);
break;
case "GET":
case "DELETE":
$this->_request = $this->cleanInputs($_GET);
break;
case "PUT":
parse_str(file_get_contents("php://input"),$this->_request);
$this->_request = $this->cleanInputs($this->_request);
break;
default:
$this->response('',406);
break;
}
}
private function cleanInputs($data){
$clean_input = array();
if(is_array($data)){
foreach($data as $k => $v){
$clean_input[$k] = $this->cleanInputs($v);
}
}else{
if(get_magic_quotes_gpc()){
$data = trim(stripslashes($data));
}
$data = strip_tags($data);
$clean_input = trim($data);
}
return $clean_input;
}
private function set_headers(){
header("HTTP/1.1 ".$this->_code." ".$this->get_status_message());
header("Content-Type:".$this->_content_type);
}
}
?>
And the API itself:
<?php
require_once("Rest.inc.php");
class API extends REST {
public $data = "";
private $db = NULL;
private $conn = NULL;
public function __construct(){
parent::__construct();
$this->dbConnect();
}
/*
* Connect to Database
*/
private function dbConnect(){
$this->conn = null;
$servername="myServer";
$dbname="mySQL";
$username="myUN";
$password="myPW";
try{
$this->conn = new PDO("mysql:host=$servername;Database=$dbname",$username, $password);
}catch(PDOException $e){
echo "Failed:" . $e->getMessage();
}
return $this->conn;
}
/*
* Dynmically call the method based on the query string
*/
public function processApi(){
//$func = strtolower(trim(str_replace("/","",$_REQUEST['x']))); //<<--NEED TO FIX THIS. x determines which function to call
$func = 'quote';
if((int)method_exists($this,$func) > 0){
$this->$func();
}else{
$this->response(404,'','');
}
}
private function quote(){
if($this->get_request_method() != "GET"){
$this->response(406, '', '');
}
$id = (int)$this->_request['id'];
if($id > 0){
try{
$sql = "SELECT * FROM mysql.Quotes WHERE ID =:ID";
$query = $this->conn->prepare($sql);
$query->bindParam(":ID", $id);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}catch(PDOException $e){
echo "Failed:" . $e->getMessage();
}
echo $this->response(200,"Success",$result);
}
}
// Initiate Library
$api = new API;
$api->processApi();
?>
One issue I'm aware of is that the commented portion in processAPI() does not work. It's supposed to grab the initial part of the URL and determine which function to run based on based on that, but my server keeps throwing an error. My workaround for the time being is just to hard-code $func = 'quote';
More importantly, though, the API returns an empty object whenever it runs. It connects to the DB and executes without errors, and it does return an object as designed -- there just isn't anything inside it. If I pull out the core components -- the DB connection, the SQL request, and the response function -- and run them on their own, they correctly pull the data and pass it on to the shell. So something in the REST class or the API must be fouling it up, but I'm not handy enough in PHP yet to figure out where it's going wrong. I'd appreciate any feedback.

How can I complete my dropdown with database data?

I'm building an application based on Slim Framework, and I already have some working code. To return a JSON response with a list of projects, I wrote the following:
Controller class (controllerProyectos.php)
<?php
require "transferController/transferProyectos.php";
class NombreProyecto {
public function getProyectos() {
$list = array();
foreach ($this->fillObject() as $sKey => $oValue) {
$list[] = array(
'id' => $oValue->getId(),
'nombre_proyecto' => $oValue->getNombre(),
'state' => $oValue->getState(),
);
}
return $list;
}
private function fillObject() {
$aObjects = array();
for ($i = 0; $i < 5; $i++) {
$oTransfer = new TransferProyeCtr();
$oTransfer->setId($i);
$oTransfer->setNombre("proyecto " . $i);
$oTransfer->setState(1);
$aObjects[] = $oTransfer;
}
return $aObjects;
}
}
Front controller (index.php)
<?php
require "vendor/autoload.php";
$sPathApi = "/api/sistemaTareas/";
$app = new \Slim\Slim();
$app->get($sPathApi . $sVersion . 'proyectos', function () {
require "controller/controllerProyectos.php";
$oProyecto = new NombreProyecto();
header('Content-Type: application/json');
echo json_encode($oProyecto->getProyectos());
exit();
});
Model class (transferProyectos.php)
<?php
class TransferProyeCtr {
private $sNombre;
private $iId;
private $iState;
public function getNombre() {
return $this->sNombre;
}
public function setNombre($nombre) {
$this->sNombre = $nombre;
}
public function getId() {
return $this->iId;
}
public function setId($Id) {
$this->iId = $Id;
}
public function getState() {
return $this->iState;
}
public function setState($state) {
$this->iState = $state;
}
}
As you can see I'm using some mockup data in the controller. When I do an AJAX request to my application, I get the following result in a dropdown:
- proyecto 1
- proyecto 2
- proyecto 3
- proyecto 4
- proyecto 5
So far everything is working as expected. But I'd like to return real data from the database in that controller.
I wrote a function (inside bdconnection.php file) to open the database connection:
<?php
function connect_db() {
$server = 'localhost';
$user = 'root';
$pass = '123asd';
$database = 'bd_actividades';
$connection = new mysqli($server, $user, $pass, $database);
return $connection;
}
I think that in my controller I need something like:
public function getPro() {
require "sistema/bdconnection.php";
$sql = "select pro_nombre FROM act_proyecto";
try {
$db = connect_db();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo json_encode($e->getMessage());
}
}
And replace $oTransfer->setNombre("proyecto " . $i); for $oTransfer->setNombre($users);, but I'm not sure.
Just to give you guys a little more detail about my application, here will go the files structure and database data:

PHP - Using classes to fetch user info

Assume the connection to the database and all references to tables and cells is correct... how could I get something like this working?
class User
{
private $_display;
private $_email;
public function __construct($username)
{
$fetch_user = mysql_query("SELECT * FROM `registered_users` WHERE `user_name`='$username'");
$fetch_user = mysql_fetch_array($fetch_user);
$this->_display = $fetch_user['user_display'];
$this->_email = $fetch_user['user_email'];
}
}
$person1 = new User('username');
echo "Information: " . print_r($person1, TRUE);
the problem is it returns nothing. Doesn't thrown an error or anything when debugged. Is it viable method though? :S
Here is roughly what I would do:
<?php
class User{
private $username;
private $data;
public function __construct($username){
$this->username = $username;
if($this->valid_username()){
$this->load();
}
}
private function load(){
// Let's pretend you have a global $db object.
global $db;
$this->data = $db->query('SELECT * FROM registered_users WHERE user_name=:username', array(':username'=>$this->username))->execute()->fetchAll();
}
public function save(){
// Save $this->data here.
}
/**
* PHP Magic Getter
*/
public function __get($var){
return $this->data[$var];
}
/**
* PHP Magic Setter
*/
public function __set($var, $val){
$this->data[$var] = $val;
}
private function valid_username(){
//check $this->username for validness.
}
// This lets you use the object as a string.
public function __toString(){
return $this->data['user_name'];
}
}
How to use:
<?php
$user = new User('donutdan');
echo $user->name; //will echo 'dan'
$user->name = 'bob';
$user->save(); // will save 'bob' to the database

Categories