What's the right way to send user input to a class?
Foo class:
<?php
class Foo
{
private $_bar;
private setBar($bar)
{
$this->_bar = $bar;
}
}
?>
Using foo class...
<?php
$foo = new Foo();
$foo->setBar((int) $_POST['input']);
?>
Or should I do the following?
开发者_JAVA技巧Foo class:
<?php
class Foo
{
private $_bar;
private setBar($bar)
{
$this->_bar = (int) $bar;
}
}
?>
Using foo class...
<?php
$foo = new Foo();
$foo->setBar($_POST['input']);
?>
Should I convert data inside of the get method or pass data to classes already converted? What's the best approach? Why?
Better yet would be to validate by an exception. If you add another method like:
public function calculateSalary() {
// uses bar, wants int
return 100 * $this->_bar;
}
and someone uses the class like this:
$foo = new Foo();
$foo->setBar('My Name Here');
echo $foo->calculateSalary(); // will give a result since php is forgiving
To avoid mishaps like these, I write setters similar to this:
public function setFoo($number) {
if(!is_numeric($number)) {
throw new Exception(__METHOD__." wants a number!");
}
$this->_foo = $number;
}
Arguments against #1: user might not include (int)
and therefor data with the wrong type is set in the object.
Arguments against #2: (see example above). PHP is translating a string to 0
if used while calculating. That means you probably will get an error without even knowing about it until you check the results.
bar
is an int. So setBar
should get an int (first option). If you want to force it into an int, I would expect a function called setBarFromString
(or something like that).
setBar
might trhow an exception on receiving a non-int.
It's better to make the validation at the inner level possible, so there is no way to end up storing invalid values inside the class (or the database or ...). Of course, that doesn't mean that you couldn't also perform validation at an outer level to save some cycles. So I would choose the second example.
Define your class's API and work backwards from there.
In this case, forcing the class to store int
s probably makes the most sense, and you can guarantee that only in the second example.
精彩评论