nighthawk wrote:So, what can you tell me about advantages and disadvantages of these two approaches.
Both of your approaches are essentially procedural, so neither is better.
nighthawk wrote:As far as I can say, not creating additional variables would decrease memory usage slightly (or am I wrong), but on larger projects this kind of code would get too cumbersome, at least for me. On the other hand, for some simpler things, the latter approach seems more elegant because there's less code involved.
I agree that you should not worry about memory much, except obvious allocation of many vars/elements. In fact, trying to save memory can sometimes cause more memory use -- don't try to outguess the optimizations.
nighthawk wrote:I know basics of OOP and I use it for every project including more than about 100 lines of code. However I have a nagging question.
I get the sense that you are using the OO language constructs, but you are not actually programming OO. One rule to generally follow is that an object should be usable upon instantiation. Caveat - there are a number of good OO practices that do not follow this rule (you will need to learn those), but in general it is the rule to follow.
So this would be preferable:
Code: Select all
class Example
{
private $_foo;
private $_bar;
public function __construct ($foo,$bar)
{
$this->_foo = $foo;
$this->_bar = $bar;
}
public function insert()
{
if($this->check()){
//insert into DB or do some other things
}
}
protected function check()
{
//some validation code, return true or false
}
}
Likewise with requinix's code, a next step would be to make it more like a Value Object. Imagine you got this object from your Model when you asked for a User. The Model would fill in the data (perhaps the constructor should take a row array) and then you could change fields. Or you could create a new user object, with no $id, and give it back to the Model to insert.
Code: Select all
class User
{
private $id;
private $firstname;
private $lastname;
private $email;
private $address;
private $city;
private $state;
private $zip;
private $country;
public function __construct($id, $firstname, $lastname, $address, $city, $state, $zip, $country)
{
$this->setId($id);
$this->setName($firstname, $lastname);
$this->setAddress($address, $city, $state, $zip, $country);
}
public function setId($id)
{
$this->id= $id;
}
public function setName($firstname, $lastname)
{
$this->firstname = $firstname;
$this->lastname = $lastname;
}
public function setAddress($address, $city, $state, $zip, $country)
{
$this->address = $address;
$this->city = $city;
$this->state = $state;
$this->zip = $zip;
$this->country = $country;
}
public function save()
{
if ($this->id) {
// update
} else {
// insert
}
}
public function validate()
{
//
}
}
PS - I'd recommend protected over private, unless you absolutely know that you want to forbid a child class from accessing a property.