PHP, passing parameters to object method or using instance variables - php

This is something I have never been fully sure of or never found a solid answer for.
Lets say I have a User class with a register() method inside it and I'm not sure which way is best to implement this method.
In my register.php page should I have
$user->register($_POST['firstName'], $_POST['lastName'], $_POST['username'], etc..);
and then in the register() method don't bother setting the objects attributes and just use the variables supplied in the signature of the method or should I do
$user->register();
and then in the register function do something like
$this->firstName = $_POST['firstName'];
$this->lastName = $_POST['lastName'];
etc...
Thanks in advance.

If the register method is tied to the object (the instance, not the class), the I'd have it use the internal properties which have to be set in advance. So, you instantiate a user, set the properties and then call $user->register().
$user = new User();
$user->firstName = 'name'; //$user->setFirstName('name') could also work
$user->lastName = 'last name'; // for this to work, the properties have to be public
$user->register();
User A should only be able to register itself, and not anything else.
If you use a method with parameters, you could basically register anything (not only a user).
Also, if registration means writing the parameters to a database, a method that only uses the internals of the user object is more robust. If you decide to change the registration mechanism (if you need some other info from the user object), only the user class has to be modified.
Edit:
Now that I've thought about it a bit more, I think I'd make another class to register users, it would take the entire user object and add a role or whatever and save it to the database. That way, a user object is a bit simpler, and does not need to know how it is registered or unregistered, and if the registration mechanism changes, the users can stay the same.
Edit 2:
Be careful when setting object properties from a method that is not a really a setter (like you would in the register($fname, $lname, ...)). The same approach has brought me headaches when "something" would change my object for no apparent reason, and I couldn't find a setter or a direct call to the property anywhere in code.

The implementation is purely up to you. You can do either way. Here is an example:
class User{
protected $_firstName = null;
protected $_lastName = null;
public function register( array $params = array() ){
if(!empty($params) ){
$this->setParams($params);
}
// Do more processing here...
}
public function setParams($params){
// Set each of the users attributes.
}
public function setFirstName($name = null){
if($name !== null){
$this->_firstName = $name;
return true;
}
return false;
}
public function getFirstName(){
return $this->_firstName;
}
// Same getter and setter methods for other attributes...
}
This way you can pass an array of User attributes to the $_POST or you can do it individually by calling $user->setFirstName(), $user->setLastName(), etc...

Considering $_POST is defined in the global scope, it would make more sense to use your latter approach (not passing in arguments and setting it up from the function). NOTE however, that this will only work in the case that $_POST is declared in the global scope (in this case) and you will lose flexibility in scenarios when you pass in the class from external PHP modules.

Related

Is fetching data from database a get-method thing?

I have a small class that I call Viewer. This class is supposed to view the proper layout of each page or something like that...
I have a method called getFirstPage, when called the user of this method will get a setting value for which page is currently set as the first page. I have some code here, I think it works but I am not really shure that I have done it the right way:
class Viewer {
private $db;
private $user;
private $firstPage;
function __construct($db, $user) {
$this->db = $db;
if(isset($user)) {
$this->user = $user;
} else {
$this->user = 'default';
}
}
function getFistPage() {
$std = $db->prepare("SELECT firstPage FROM settings WHERE user = ':user'");
$std->execute(array(':user' => $user));
$result = $std->fetch();
$this->firstPage = $result['firstPage'];
return $this->firstPage;
}
}
My get method is fetching the setting from databse (so far so good?). The problem is that then I have to use this get method to set the private variable firstPage. It seems like I should have a set method to do this, but I cannot really have a set method that just fetch some setting from database, right? Because the user of this object should be able to assume that there already is a setting defined in the object...
How should I do that?
I think your approach is not bad. The most important thing is passing $db in the constructor, which you do. The user could be parameter of the constructor or the method itself, it depends on how 'permanent' the user is, for the application.
There are several minor things I would improve:
Use type hinting for PDO object. Therefore, anyone who uses your 'library' knows what kind of object should be injected.
Almost never use private visibility, use protected instead. Therefore, if someone wants to extend your class, he still has access to your properties.
Don't use isset/empty for checking $user, rather introduce a default value. Therefore, anyone who calls your method and sees the parameters knows, what's going on.
Always explicitly use public visibility. It's a good practice and you won't confuse for example Java developers, who have package as default.
If you really want to create a high quality code, check for every possible error state so you won't encounter a fatal error. PDO::fetch can return false and you should check this error state before you access the result as an array.
If you decide to save $firstPage to the object state, you should reuse it the next time the method is called. However, if you write a common web app, I don't think you really want to put it to object state. Instead, just return the result.
Then, your code would look like this:
class Viewer {
/** #var PDO $db */
protected $db;
protected $user;
public function __construct(PDO $db, $user = 'default') {
$this->db = $db;
$this->user = $user;
}
public function getFistPage() {
$std = $this->db->prepare("SELECT firstPage FROM settings WHERE user = ':user'");
$std->execute(array(':user' => $this->user));
$result = $std->fetch();
if ($result !== false) {
return $result['firstPage'];
} else {
throw new YourException('Failed to fetch first page.');
// or return false/null;
}
}
Edit: You should always fully set up the object state in the constructor and you should not do any computation in it. Also, avoid using initialize-like methods. In this case, constructor ensures we have PDO and $user parameter set up (object state). Then, you can do your computation in the method without passing additional parameters (which is good, it supports object encapsulation).
Getters should not change the state of the object. However, sometimes member variables are not part of the actual object state - rather they are used for internal caching. You should ask yourself - is firstPage part of the state? Should users of the class care whether it was set or not? Other than performance, does the object act differently based on it's value? If not, than it's OK to set it in a getter.

Yii extending the user doesn't seem to retain additional instance variables

I have read the tutorials on how to make a sub class of CWebUser and followed the instructions. The paths all work, and the code is getting into the right methods, however the value returned from my getter is always nil.
class PersonUser extends CWebUser {
// Store model to not repeat query.
private $_person;
// Load user model.
public function loadPerson($id=null, $duration=0)
{
$this->login($id,$duration);
$this->_person=Person::model()->findByPk(Yii::app()->user->id);
}
public function getPerson()
{
return $this->_person;
//return Person::model()->findByPk($this->id);
}
}
If I echo in the loadPerson method $this->_person->first_name after I set _person I get the value I expect. However, at any later time, if I ask for Yii::app()->user->person, the getPerson() method gets called, but $this->_person is now null. I know it's getting in there, if I uncomment the line below and have it look up the person every time, it works.
Is this an issue with Yii? I would really like to be able to cache the person object so I can reference it throughout the session without having to make more calls to the database. What am I missing??
There is no issue with Yii....
As per the documentation, CWebUser class identifies predefined variables "id" and "name" which remains persistent through out the session. Any additional variables should be used with getState() and setState() methods.
" Moreover CWebUser should be used together with IUserIdentity Class which implements the actual authentication algorithm. "
The method loadUser() is never called. And the login() call inside also doesn't make sense. A simpler implementation of getPerson() would be.
private $_person = false;
public function getPerson()
{
if($this->_person===false)
$this->_person = Person::model()->findByPk($this->id);
return $this->_person;
}

Repetitive class (method/property) invoking in PHP

The following is an excerpt from some code I wrote to assign the $user->privilege based on a method from that same class. It seems excessively repetitive, and I am wondering if there is something I can do to make it more readable -- given that I haven't seen this kind of repetition too much in codes I have looked at.
$user -> privileges = $user -> get_privileges ( $user -> username );
It doesn't look particularly repetitious to me, but it is a little unusual to be assigning an object's property based on a method outside the class. Instead, this might be better handled inside the object constructor, eliminating the need for you to remember to set the property when coding:
class User {
public $username;
public $privileges;
public function __construct() {
// setup the user however that's done...
// And assign privileges in the constructor
$this->privileges = $this->get_privileges();
}
// In get_privilegs, rather than passing the username property,
// just access it via $this->username.
// Unless you need to use this method from time to time outside the class, it can be private
private function get_privileges() {
// Get privs for $this->username
}
}
And as an alternative to $this->privileges = $this->get_privileges(); called in the constructor, you might just set $this->privileges inside the get_privileges() method. Then you can just call it as $this->get_privileges() in the constructor, no assignment necessary. Either way works.
I use this pattern a lot when a method is expensive and I can just store the result for the remainder of the request:
class User {
protected $_privileges = null;
public function getPrivileges() {
if ($this->_privileges == null) {
// code to populate privileges array
$this->_privileges = $privileges;
}
return $this->_privileges;
}
}
That way getPrivileges() will only do the hard work once and afterward it uses its own locally cached copy for the remainder of the request for that object instance.

Object Oriented PHP Best Practices

Say I have a class which represents a person, a variable within that class would be $name.
Previously, In my scripts I would create an instance of the object then set the name by just using:
$object->name = "x";
However, I was told this was not best practice? That I should have a function set_name() or something similar like this:
function set_name($name)
{
$this->name=$name;
}
Is this correct?
If in this example I want to insert a new "person" record into the db, how do I pass all the information about the person ie $name, $age, $address, $phone etc to the class in order to insert it, should I do:
function set($data)
{
$this->name= $data['name'];
$this->age = $data['age'];
etc
etc
}
Then send it an array? Would this be best practice? or could someone please recommend best practice?
You should have setter/getter methods. They are a pain but you don't necessarily have to write them yourself. An IDE (for example Eclipse or Netbeans) can generate these for you automatically as long as you provide the class member. If, however, you don't want to deal with this at all and you're on PHP5 you can use its magic methods to address the issue:
protected $_data=array();
public function __call($method, $args) {
switch (substr($method, 0, 3)) {
case 'get' :
$key = strtolower(substr($method,3));
$data = $this->_data[$key];
return $data;
break;
case 'set' :
$key = strtolower(substr($method,3));
$this->_data[$key] = isset($args[0]) ? $args[0] : null;
return $this;
break;
default :
die("Fatal error: Call to undefined function " . $method);
}
}
This code will run every time you use a nonexistent method starting with set or get. So you can now set/get (and implicitly declare) variables like so:
$object->setName('Bob');
$object->setHairColor('green');
echo $object->getName(); //Outputs Bob
echo $object->getHairColor(); //Outputs Green
No need to declare members or setter/getter functions. If in the future you need to add functionality to a set/get method you simply declare it, essentially overriding the magic method.
Also since the setter method returns $this you can chain them like so:
$object->setName('Bob')
->setHairColor('green')
->setAddress('someplace');
which makes for code that is both easy to write and read.
The only downside to this approach is that it makes your class structure more difficult to discern. Since you're essentially declaring members and methods on run time, you have to dump the object during execution to see what it contains, rather than reading the class.
If your class needs to declare a clearly defined interface (because it's a library and/or you want phpdoc to generate the API documentation) I'd strongly advise declaring public facing set/get methods along with the above code.
Using explicit getters and setters for properties on the object (like the example you gave for set_name) instead of directly accessing them gives you (among others) the following advantages:
You can change the 'internal' implementation without having to modify any external calls. This way 'outside' code does not need change so often (because you provide a consistent means of access).
You provide very explicitly which properties are meant to be used / called from outside the class. This will prove very useful if other people start using your class.
The above reasons is why this could be considered best practice although it's not really necessary to do so (and could be considered overkill for some uses ; for example when your object is doing very little 'processing' but merely acts as a placeholder for 'data').
I perfectly agree with CristopheD (voted up). I'd just add a good practice when creating a new person.
Usually, a use a constructor which accept the mandatory fields and set the default values for the optional fields. Something like:
class Person
{
private $name;
private $surname;
private $sex;
// Male is the default sex, in this case
function Person($name, $surname, $sex='m'){
$this->name = $name;
$this->surname = $surname;
$this->sex = $sex;
}
// Getter for name
function getName()
{
return $this->name;
}
// Might be needed after a trip to Casablanca
function setSex($sex)
{
$this->sex = $sex;
}
}
Obviously, you could use the setter method in the constructor (note the duplicate code for the sex setter).
To go full OOP, you should do something similar to:
class User {
private $_username;
private $_email;
public function getUsername() {
return $this->_username;
}
public function setUsername($p) {
$this->_username = $p;
}
...
public function __construct() {
$this->setId(-1);
$this->setUsername("guest");
$this->setEmail("");
}
public function saveOrUpdate() {
System::getInstance()->saveOrUpdate($this);
}
}
If you want to save a user, you just create one, assign its values using Setters and do $user->saveOrUpdate(), and have another class to handle all the saving logic.
As a counterpoint to ChristopheD's answer, if your instance variable is strictly for private use, I wouldn't bother with writing a getter & setter, and just declare the instance variable private.
If other objects need to access the object, you can always add a getter. (This exposes another problem, in that other classes might be able to change the object returned by the getter. But your getter could always return a copy of the instance variable.)
In addition using a getter/setter also shields other parts of the same class from knowing about its own implementation, which I've found very useful on occasion!
From a more general point of view both direct access ($person->name) and accessor methods ($person->getName) are considered harmful. In OOP, objects should not share any knowledge about their internal structure, and only execute messages sent to them. Example:
// BAD
function drawPerson($person) {
echo $person->name; // or ->getName(), doesn't matter
}
$me = getPersonFromDB();
drawPerson($me);
// BETTER
class Person ....
function draw() {
echo $this->name;
}
$me = getPersonFromDB();
$me->draw();
more reading: http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

Feedback on a session storage class design

I have a session class that basicly just sets and retrieves session variables,
the reason I made it was so I could easily change it to use sessions or something
like memcache to set the items and have them accessible on multiple pages without hitting the database
I then have this user class which uses the session object to get session variables in it.
I am wanting to add to this user class though, to make it more encapsulated I would like to be able to set the variables that I am retrieving in this class
so right now I can display the userid with $user->userid; I would like to first have a method or something that sets its value from the session object I guess
Does this sound lke a good idea or possibly a lot of overhead?
And if what I am trying to do is a good idea maybe you could suggest/show example of how I should do it? I am thinking that if I add that method in that possibly I should move the code in the __construct method into it's own method
Basicly, I have the variables listed in the top part of the class that are used in the construct method, if I have multiple methods in the class though would I need to set them all at the top like that?
<?PHP
//user.class.php file
class User
{
public $userid;
public $name;
public $pic_url;
public $gender;
public $user_role;
public $location_lat;
public $location_long;
public $newuser;
function __construct()
{
global $session;
if($session->get('auto_id') != ''){
//set user vars on every page load
$this->userid = $session->get('auto_id'); //user id number
$this->name = $session->get('disp_name');
$this->pic_url = $session->get('pic_url');
$this->gender = $session->get('gender');
$this->user_role = $session->get('user_role');
$this->location_lat = $session->get('lat');
$this->location_long = $session->get('long');
$this->newuser = $session->get('newregister');
}else{
return false;
}
}
}
//with the class above I can easily show some user variables I have saved into a session like this below
$user = new user();
$user->userid;
?>
In general your idea is a good one
3 things I would do differently:
1) In your implementation doesn't seem to consider having several users. ie Several instances of the same class.
2) I would use factories instead of using IF in the constructor.
So for a user you have saved in the session you would call:
$savedUser = User::fromSession($userId);
for a new user
$user = new User()
3) Use the serialize and unserialze functions to save that data to the session
Then your class could could be implemented as
public static function fromSession($userId) {
return unserialize($session->get('users_'.$userId));
}
public function save() {
return $session->set('users_'.$this->id , serialize($this));
}
I guess this is vaguely an answer to the "is this a good idea" question. In my understanding, locating variables in the session versus refreshing them from the database is a question of the trade off between complex queries and deserializing data. The session data isn't a free magic cache that escapes database calls, it is just a convenient wrapper around a database call that you don't have to deal with. Any variable that you place in the session must be serializable. The whole collection of serialized data is then managed; the server fetches the data using the session key, deserializes it all, and hands it to the php script. Then when it closes the session for that request-response cycle it serializes it all and puts it back in the db.
So the mess in dealing with all that can, in some cases, be worse than the mess of just opening a connection and asking the db for the same stuff (or a subset of stuff) directly.
I would say that putting one or two key values in the session is a good stopping place, and relying on it too heavily for statefulness is a less-optimal plan.
I would set a new session with a name like "ValuesInSession" to true or false depending on whether or not you have session values for the fields in your user class. Then, in the sessions\users class you can check whether this session is true or false and set your values accordingly (IE from the existing sessions or to empty strings\0)
EDIT: You could, alternatively to putting that code in the user or sessions class, write a new class which could work with your users class to set the values properly (perhaps it could extend the sessions class?)
I'm not sure I understand the question, however, if you are using php 5, you can use the __set magic method to help with this.
Modifying your current class:
class User
{
private $id;
private $data = array();
public function __construct()
{
global $session;
$this->id = $session->get('auto_id');
$this->data = array(
'disp_name'=>$session->get('disp_name'),
'pic_url'=>$session->get('pic_url'),
'gender'=>$session->get('gender'),
'user_role'=>$session->get('user_role'),
'lat'=>$session->get('lat'),
'long'=>$session->get('long'),
'newregister'=>$session->get('newregister')
);
}
// return the user id
public function id()
{
return $this->id;
}
// the __get magic method is called when trying to retrieve a value of a
// property that has not been defined.
public function __get($name)
{
if(array_key_exists($name, $this->data))
{
return $this->data[$name];
}
return null;
}
// the __set magic method is called when trying to store a value in a property
// that has not been defined.
public function __set($name, $value)
{
global $session;
// check if the key exists in the 'data' array.
// if so, set the value in the array as well as the session
if(array_key_exists($name, $this->data))
{
$this->data[$name] = $value;
$session->set($name, $value);
}
}
}
This way you can still get and set values the same as you were, but will also store the set the value in your session class.
To test this:
$user = new User;
if($user->id())
{
echo $user->disp_name;
$user->disp_name = 'new name';
echo $session->get('disp_name');
}
I would not suggest you that because:
It is not a good practice to select an architecture "in case of future need" ('the reason I made it was so I could easily change'). Check http://www.startuplessonslearned.com (Eric Ries) or http://highscalability.com articles
Your code is hard/impossible to test (See Misko Hevery's blog (A google evangelist) http://misko.hevery.com for further information).
You are using "global" (never a good idea if you want to keep track of the dependencies).
It is better to seperate "the business logic" (a User class) and the wiring/building (a factory class for example). (See http://en.wikipedia.org/wiki/Single_responsibility_principle and "separation of concerns")
For really good code examples (and to understand which OO laws should not be broken), I can advice you Misko's blog (Also do not miss his technical talks at google that you can find on youtube). I am sure you will love them.
Hope this helps.

Categories