I beautiful people,
another question for a laravel novice: for now I'm following a course of laravel 4 and the teacher did a code refactoring and introduced a magic method constructor in the controller
class UtentiController extends BaseController {
protected $utente;
public function __construct(Utenti $obj) {
$this->utente = $obj;
}
public function index() {
$utenti = $this->utente->all();
return View::make('utenti.index', ["utenti" => $utenti]);
}
public function show($username) {
$utenti = $this->utente->whereusername($username)->first(); //select * from utenti where username = *;
return View::make('utenti.singolo', ["utenti" => $utenti]);
}
public function create() {
return View::make('utenti.create');
}
public function store() {
if (! $this->utente->Valido( $input = Input::all() ) ) {
return Redirect::back()->withInput()->withErrors($this->utente->messaggio);
}
$this->utente->save();
return Redirect::route('utenti.index');
}
}
thanks to this code i can avoid every time to create a instance of the model Utenti:
protected $utente;
public function __construct(Utenti $obj) {
$this->utente = $obj;
}
now i can access to the database with this simple approach:
/* now i can access to the database simply use this method */
$this->utente->all();
before this, i had to:
$utente = new Utente;
$utente::all();
this type of tecnique have a name? (is a pattern?). Hovewer,i know what does he do: every time the controller is invoked automatically generates an instance of the User class (model) and applies an alias (reference) attribute protected $utente;
that's right? Thanks for everything.
P.S: that's the code of my User Layer model called "Utenti":
class Utenti extends Eloquent {
public static $regole = [
"utente" => "required",
"password" => "required"
];
public $messaggio;
public $timestamps = false;
protected $fillable = ['username','password'];
protected $table = "utenti";
public function Valido($data) {
$validazione = Validator::make($data,static::$regole);
if ($validazione->passes()) return true;
$this->messaggio = $validazione->messages();
return false;
}
}
Aucun commentaire:
Enregistrer un commentaire