简体   繁体   中英

Can I use an Eloquent model as a fully featured class?

I'm just learning Laravel 4 and I was unsure about how Eloquent models work. It is clear to me that they are a good way to interact with the database but can I define constructors and functions on a class that extends Eloquent to use it for more than database interaction?

Yes! A class that extends Eloquent, doesn't make it a class solely used for Eloquent purposes. You've got the realize the concept of class extension. Class extension is there to simply add features to ANY class from another, existing class. In this case Eloquent.

You can take any model you already have, and tomorrow decide that you want to use it with Eloquent and simply extend it. Your original class is still your original class and works the same. Any methods or properties in the original class will ovewrite its parent (Eloquent) if the parent has something with the same name.

In fact, creating other methods in a class that extends Eloquent is the real way to create robust models that do all sorts of cool stuff. I create methods in my User model for example, to calculate how many day's until their birthday. Instead of pulling the birthday column into a controller then using PHP to do the calculation, I just have a method like User::daysUntilBirthday();

If you use a constructer and extend Eloquent, make sure you still fire off Eloquent's constructor as well though.

class MyModel extends Eloquent {

   public function __construct($attributes = array(), $exists = false)
   {
      parent::__construct($attributes, $exists); // This will fire off Eloquent's constructor.
      // Your construct code.
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM