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.
Related
I'm in the process of re factoring a lot of code to make it more testable and I have a bunch of useful functions that rely on an instantiated database object.
Things like this:
function id_from_name($table, $name)
{
$db = get_database();
//code that returns an id
}
function username_from_user_id($id)
{
$db = get_database();
//code that returns a username
}
There are a bunch more like id_exists, id_active etc.
Now I'm thinking that this isn't the right thing to do as the object should probably be passed through as an argument? But then that means creating and sending in a new object into each of these functions every time i want to use one.
So really, my questions are: Should I be moving these functions into their own class/library that has access to the database object? and are the examples that I've shown above generally a bad way of doing things?
A better approach would be indeed to make classes. And you would be passing the database object to the constructor and make it an instance variable. That way every function would have access to the database object.
Now the reason why it is considered bad to instantiate e.g. your database object in every function, is because if you decide for example one day to change your datasource, you might need a huge refactor. If you pass your database object into the constructor, you can just pass/inject the right object into the class without any refactor.
...a bit more about DI below...
By passing your objects into the constructors, you also create a more clear API => you know which object depends on the other, you know exactly which class uses your DB object. If you start instantiating it or accessing it in a static way inside the functions like you did, I would have to look through all your classes to see where your DB object is used. One more point, dependency injection forces SRP (single responsibility principle) => if you start injecting too many objects (constructor gets many arguments), you should suspect your class is doing too much than what it should, and start refactoring.
You can create a class Table_Adapter and instantiate database object inside its constructor:
class Table_Adapter
{
protected $db;
public function __construct()
{
$db = get_database();
}
}
Then you create a child class Items_Table_Adapter' that extendsTable_Adapterand put their all methods related toItems` table.
class Items_Table_Adapter extends Table_Adapter
{
public function item_by_id($id)
{
}
}
Then you use it like:
$tableAdapter = new Items_Table_Adapter();
$item = $tableAdapter->item_by_id(1);
Try something like:
class YourClass{
public static function get_database(){
// your creation
return $db;
}
public function id_from_name($table, $name)
{
/* your code */
//code that returns an id
}
public function username_from_user_id($id)
{
/* your code */
}
}
so you could just use it this way:
$db = YourClass::get_database();
$result = $db->id_from_name($table, $name);
It is certainly recommended that you have the option to swap out your database connection.
Now, if your function get_database() looks like this:
function get_database() {
static $db;
if (!$db)
$db = new \mysqli(...);
return $db;
}
Then you really, really should change it to a wrapper around a class, looking like this:
function get_database_manager() {
static $dbmgr;
if (!$dbmgr)
$dbmgr = new DbManager;
return $dbmgr;
}
function get_database() {
return get_database_manager()->getCurrentConnection();
}
where DbManager has an instance attribute with the current connection that is returned with getCurrentConnection(). If you want to swapt out the connection, do something like get_database_manager()->setConnection($newConn). Problem solved :)
I'll leave the downsides of static programming here (it remains with many examples in this thread): http://kunststube.net/static/
as well as the common method to get rid of that (we have another approach here): http://en.wikipedia.org/wiki/Dependency_injection
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.
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.
I have some code that often looks like this:
private $user;
public function __construct()
{
$this->user = User::getInstance(); //singleton
}
public function methodOne()
{
return $this->user->foo();
}
public function methodTwo()
{
return $this->user->foo2();
}
public function methodThree()
{
return $this->user->foo3();
}
I figure if I set user property to the instance I can reuse a shorter name in my methods (well in this case it's not that much shorter). I also thought doing it this way might save a little resources (beginning to doubt it), but when I look at other people's code I rarely see people do this. They would usually just call:
User::getInstance()->foo();
User::getInstance()->foo2();
User::getInstance()->foo3();
Is there any sort of best practice for this? Maybe if it's not a singleton class you might do it this way? Or maybe you should never do it this way? Hope to get some clarification, thanks.
Edit:
Incase there is any misunderstanding I'm just wondering if I should the first example with creating a property to store the instance vs this:
public function methodOne()
{
return User::getInstance()->foo();
}
public function methodTwo()
{
return User::getInstance()->foo2();
}
public function methodThree()
{
return User::getInstance()->foo3();
}
Actually now that I think about it this may be less code as I don't need the constructor...
There are indeed some problems with your approach.
It is not clear that your class depends on the User class. You can solve this with adding User as a constructor parameter.
Singletons are often bad practice. Your code demonstrates why: it is globally accessible and hence difficult to track dependencies using it (this points to the above problem).
Static methods are too often used as global access points (in response to what you see people usually do User::method()). Global access points give the same problem as singletons. They are also a tad more difficult to test.
I also don't see the point in repeating the User object with your new object, unless you would use eg the adapter pattern. Maybe if you could clarify this I would be able to come up with a better alternative than the generic:
class Foo {
public function __construct(User $user) {
$this->user = $user;
}
public function doXsimplified() {
$this->user->doXbutMoreComplex($arg1,$arg2, $arg20);
}
}
My personal preference in PHP is to use classes with just static methods for singletons, so you have
User::foo();
User::bar();
I would not create a new class just to wrap around a singleton like that. But if your new class adds some extra logic then your example makes sense. Remember, if you're worried that you're too verbose you can always use a temporary variable for successive function calls.
$user = User::getInstance();
$user->foo();
$user->bar();
But personally, I don't use Singletons anymore. Instead, I use Dependency Injection. I like the sfServiceContainer, but there are others. Have a look at this series of articles: http://fabien.potencier.org/article/11/what-is-dependency-injection
UPDATE
Based on the additional comments, this is how I would do it:
class UserWrapper
{
private $user = null;
public function __construct($user)
{
$this->user = $user;
}
public function foo()
{
return $this->user->foo();
}
...
}
Then use it like this:
$user = new UserWrapper(User::getInstance());
Why? So I can pass in a fake User object if I want to test the UserWrapper class. E.g:
class UserMock { ... } // A fake object that looks like a User
$userTest = new UserWrapper(new UserMock());
I usually go like this, if you have already included the class in a bootstrap of some sort or a config file. I would usually declear the $user variable in a bootstrap that will get called on every page load, then just reference it as a global variable on other php files, this is what I would have in the bootstrap file.
$user = new User();
Then this is what I would have in the calling php file
global $user;
$user->foo();
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.