Is there any reason why we only have this static way to boot traits in Laravel:
static function bootMyTrait ()
{...}
Is there any way to boot trait and have model instance in the boot function? Like this:
function bootMyTrait ()
{
if ($this instanceOf awesomeInterface)
{
$this->append('nice_attribute');
}
}
I need this AF, and for a very long time haven't found any solution.
Since Laravel 5.7 you can use trait initializers, instead of trait booters. I've had the same task and was able to solve it like this:
public function initializeMyTrait()
{
if ($this instanceOf awesomeInterface)
{
$this->append('nice_attribute');
}
}
Well, no one seems to care :D
Good news, is that within 15 min, I've solved my problem with this in base model:
public function __construct(array $attributes = [])
{
foreach (class_uses_recursive($this) as $trait)
{
if (method_exists($this, $method = 'init'.class_basename($trait))) {
$this->{$method}();
}
}
parent::__construct($attributes);
}
Edit
Instead of relying on traits for this, use Eloquent's accessors and mutators. For example, define the following methods on a User model:
// Any time `$user->first_name` is accessed, it will automatically Uppercase the first letter of $value
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
This appends the $user->first_name attribute to the model. By prefixing the method name with get and suffixing it with Attribute you are telling Eloquent, Hey, this is an actual attribute on my model. It doesn't need to exist on the table.
On the other hand you can define a mutator:
// Any string set as first_name will automatically Uppercase words.
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = ucwords($value);
}
This will apply anything you do to $value before setting it in the $attributes array.
Of course, you can apply these to attributes that do exist on your database table. If you have raw, unformatted data, say a telephone number 1234567890, and you wanted to apply a country code, you could use an accessor method to mask the number without modifying the raw value from the database. And going the other way, if you wanted to apply a standard formatting to a value, you could use a mutator method so all your database values conform to a common standard.
Laravel Accessor and Mutators
Related
Edit function:
public function editCheck($id, LanguagesRequest $request)
{
try{
$language = language::select()->find($id);
$language::update($request->except('_token'));
return redirect()->route('admin.languages')->with(['sucess' => 'edit done by sucsses']);
} catch(Exception $ex) {
return redirect()->route('admin.addlanguages');
}
}
and model or select function
public function scopeselect()
{
return DB::table('languages')->select('id', 'name', 'abbr', 'direction', 'locale', 'active')->get();
}
This code is very inefficient, you're selecting every record in the table, then filtering it to find your ID. This will be slow, and is entirely unnecessary. Neither are you using any of the Laravel features specifically designed to make this kind of thing easy.
Assuming you have a model named Language, if you use route model binding, thing are much simpler:
Make sure your route uses the word language as the placeholder, eg maybe your route for this method looks like:
Route::post('/languages/check/{language}', 'LanguagesController#editCheck');
Type hint the language as a parameter in the method:
public function editCheck(Language $language, LanguagesRequest $request) {
Done - $language is now the single model you were afer, you can use it without any selecting, filtering, finding - Laravel has done it all for you.
public function editCheck(Language $language, LanguagesRequest $request) {
// $language is now your model, ready to work with
$language::update($request->except('_token'));
// ... etc
If you can't use route model binding, or don't want to, you can still make this much simpler and more efficient. Again assuming you have a Language model:
public function editCheck($id, LanguagesRequest $request) {
$language = Language::find($id);
$language::update($request->except('_token'));
// ... etc
Delete the scopeselect() method, you should never be selecting every record in your table. Additionally the word select is surely a reserved word, trying to use a function named that is bound to cause problems.
scopeselect() is returning a Collection, which you're then trying to filter with ->find() which is a method on QueryBuilders.
You can instead filter with ->filter() or ->first() as suggested in this answer
$language = language::select()->first(function($item) use ($id) {
return $item->id == $id;
});
That being said, you should really find a different way to do all of this entirely. You should be using $id with Eloquent to get the object you're after in the first instance.
I have a question about extending my own Models eloquent.
In the project I am currently working on is table called modules and it contains list of project modules, number of elements of that module, add date etc.
For example:
id = 1; name = 'users'; count = 120; date_add = '2007-05-05';
and this entity called users corresponds to model User (Table - users) so that "count" it's number of Users
and to update count we use script running every day (I know that it's not good way but... u know).
In that script is loop and inside that loop a lot of if statement (1 per module) and inside the if a single query with count. According to example it's similar to:
foreach($modules as $module) {
if($module['name'] == 'users') {
$count = old_and_bad_method_to_count('users', "state = 'on'");
}
}
function old_and_bad_method_to_count($table, $sql_cond) {}
So its look terrible.
I need to refactor that code a little bit, because it's use a dangerous function instead of Query/Builder or Eloquent/Model and looks bad.
I came up with an idea that I will use a Models and create Interface ElementsCountable and all models that do not have an interface will use the Model::all()->count(), and those with an interface will use the interface method:
foreach ($modules as $module) {
$className = $module->getModelName();
if($className) {
$modelInterfaces = class_implements($className);
if(isset($modelInterfaces[ElementsCountable::class])) {
/** #var ElementsCountable $className */
$count = $className::countModuleElements();
} else {
/** #var Model $className */
$count = $className::all()->count();
}
}
}
in method getModelName() i use a const map array (table -> model) which I created, because a lot of models have custom table name.
But then I realize that will be a good way, but there is a few records in Modules that use the same table, for example users_off which use the same table as users, but use other condition - state = 'off'
So it complicated things a little bit, and there is a right question: There is a good way to extends User and add scope with condition on boot?
class UserOff extends User
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(function (Builder $builder) {
$builder->where('state', '=', 'off');
});
}
}
Because I have some concerns if this is a good solution. Because all method of that class NEED always that scope and how to prevent from method withoutGlobalScope() and what about other complications?
I think it's a good solution to create the UserOff model with the additional global scope for this purpose.
I also think the solution I would want to implement would allow me to do something like
$count = $modules->sum(function ($module) {
$className = $module->getModelName();
return $className::modulesCount();
}
I would create an interface ModulesCountable that mandates a modulesCount() method on each of the models. The modulesCount() method would return either the default count or whatever current implementation you have in countModuleElements().
If there are a lot of models I would probably use a trait DefaultModulesCount for the default count, and maybe the custom version too eg. ElementsModuleCount if that is consistent.
To keep things short, the application itself is really simple, having only three tables.
Product:
id
name
Attribute
id
name
slug
Product Attribute
id
attribute_id
product_id
value
As you may guess the attributes may be totally random, with any content and there might be any number of them. Every product has the same set of global attributes assigned. Some are empty, some are filled.
What I want to do is displaying them in a standard Gridview, the same way as if it was a normal model, with dynamic-preassigned columns and values. Basically speaking - the attributes should serve as the columns.
I've tried to extend the main Product Model and use ActiveDataProvider class on it, but no avail, I'm getting the custom attributes values repeated for each row, as if something was missing. Here's the class I've created basing on another question from SO.
namespace common\models;
use Yii;
use common\models\Attribute;
use common\models\Product;
class ProductDynamic extends Product {
public function init() {
parent::init();
$attrExists = ProductAttribute::find()->select(['slug','value'])->joinWith(['attributeModel'])->all();
if ($attrExists) {
foreach ($attrExists as $at) {
$this->dynamicFields[$at['slug']] = $at['value'];
}
}
}
private $dynamicFields = [];
public function __get($name) {
if (array_key_exists($name, $this->dynamicFields))
return $this->dynamicFields[$name];
else
return parent::__get($name);
}
public function __set($name, $value) {
if (array_key_exists($name, $this->dynamicFields))
$this->dynamicFields[$name] = $value;
else
parent::__set($name, $value);
}
public function rules() {
return array_merge(parent::rules, $this->dynamicRules);
}
}
My question is - how would you do it? How to assign properties to a model so they act as a standard database-loaded properties usable by ActiveDataProvider? I think I need to retrieve the ProductAttributes some other way so they are not repeated. See below.
Ok, i think i got your idea...
So, I think you could generate an attribute in the model of Product (we will call it ProductAttributeArr) which would be an array, then retrieve the attributes from the Attribute table in the database according to Product Attribute table and store them in ProductAttributeArr.
Then you could create a function that dynamically generates the parameters for the GridView base on the content of ProductAttributeArr. This way it should work.
Answering it myself since there's no feedback and after some more digging i've found the quickest, but maybe not the nicest solution.
Since the properties in main Product model are added thanks to the ProductDynamic class I have added the following in Product to assign correct column values. For sure, there must be another, easier way, if you know any feel free to comment.
public function afterFind() {
$attrs = ProductAttribute::find()->select(['slug', 'value'])->joinWith(['attributeModel'])->where(['product_id' => $this->id])->all();
foreach ($attrs as $a) {
$this->{$a['slug']} = $a['value'];
}
}
I see two different implementations when people handle classes that extend other classes and provide functionality based on certain setting inside the class.
Variables are used to store settings.
Methods are used to return settings.
Using Variables:
class Model {
var $fields = array();
function getFields() {
return array_keys($this->fields);
}
function getRules() {
return $this->fields;
}
}
class Person extends Model {
var $fields = array(
'name' => array('maxLength'=>10),
'email' => array('maxLength'=>50, 'validEmail'=>true),
);
}
Using Methods:
class Model {
function getFields() {}
}
class Person extends Model {
function getFields() {
return array('name','email');
}
function getRules() {
return array(
'name' => array('maxLength'=>10),
'email' => array('maxLength'=>50, 'validEmail'=>true),
);
}
}
Both examples achieve the same results, I can do things like $person->getFields() and $person->getRules(), but in the method-example I don't like the "duplicate" field list, because the fields are actually defined both in $person->getFields() and $person->getRules() and it must compute the array every time it is asked for via the method. On the other hand, I don't like that every object stores all the settings in a variable. It seems like a resource waste. So I'm just wondering what's the better way.
My main questions are:
Is there a performance-reason to pick one way over the other? 2)
Is there a OOP-logic/ease-of-programming/other-reason to pick one
way over the other?
From a few benchmark tests - the times are pretty similar - the exeption though
return array('name','email');
is much faster than
return array_keys($this->fields);
Running 10,000 operations for each method produced these averages:
Variable:
getFields 0.06s
getRules 0.05s
Method:
getFields 0.04s
getRules 0.05s
To answer your second question - it depends on your use-case - if the data stored in these objects is static, or if it will come from another datasource / config file.
One follow up question, why not use object properties?
class Person extends Model {
protected $name
protected $email
public function getName() {
return $this->name;
}
public function getEmail() {
return $this->email;
}
}
My opinion is pick what you are comfortable with, there is no much performance loss or performance gain from using either. You better save the performance saving effort for data handling.
For me I use object properties, it looks clear when you are looking at the class, for storing such default properties, and if you want to override them, then use this beautiful syntax:
array()+array()
I've an ORM model (PHP Active Record), say, for a blogging system. I've something that's a post model that stores the number of likes. The post could either be a picture or quote (say), and they are different tables (and hence models).
The schema is that a post holds data like number of shares, likes, description, etc. along with either a picture or a quote.
So when writing getters for the post model I'm having to write
public function getX() {
if ($this->isPicture()) {
return $this->picture->getX();
}
else if ($this->isQuote()) {
return $this->quote->getX()
}
else {
return self::DEFAULT_X
}
}
I'm currently having to write this structure for many getter. Is there something I can do to avoid that?
PS: Tagged as PHP because that's my code in.
EDIT
Changed comments to code.
This is a model (and a corresponding table in the DB) that has more data than just a picture and quote. Example, description that's part of the post and doesn't reside on either the picture or the quote.
There's tables for pictures and quotes.
Using PHP Active Record and each of the three classes extends the generic model class provided by PHP Active Record.
The picture model has it's own data. Same for quote.
To expand on the idea of the Strategy pattern mentioned in the comments:
class Post {
// get the correct 'strategy'
public function getModel() {
if ($this->isPicture()) {
return $this->picture;
}
if ($this->isQuote()) {
return $this->quote;
}
return null;
}
// using the strategy
public function getX() {
$model = $this->getModel();
if (null === $model) {
return self::DEFAULT_X;
}
return $model->getX();
}
}
Each strategy would presumably implement the same interface as the Post class for exposing those getters. Even better would be to provide a default strategy (rather than returning null) and have that return the default values. That way, the null check in each getter becomes redundant.
An alternative approach to this is a very basic form of metaprogramming. The idea is that you go a level higher than calling your methods by hand, and let the code do it for you.
(Assume that the method definitions are all part of Post)
public function getX($model = null) {
if ($model) return $model->getX();
else return self::DEFAULT_X;
}
// usage
$postModel->getX($pictureModel);
What's happening here is that, in this single instance of getX in your Post model, you're passing in the name of another class, and executing the `getX' method on that instance (if it exists and is callable).
You can extend this in other ways. For example, maybe you don't want to pass an instance in, when the method can do it anyway:
public function getX($model_name = null) {
if ($model_name && $class_exists($model_name) && is_callable(array($model_name, 'getX')) {
$model = new $model_name;
return $model->getX();
} else {
return self::DEFAULT_X;
}
}
// usage
$postModel->getX('Picture');
In this instance, you pass the model in as a string, and the method will do the rest. While this makes it quicker to get what you want, you might find that you don't want to work with fresh instances all the time (or you can't), so there's a bit of a trade-off with this 'convenient' way.
That still doesn't fully solve your problem, though, since you still have to repeat that for each getter, over and over again. Instead, you can try something like this:
public function __call($method, $args) {
$class = $args[0];
if (class_exists($class) && is_callable(array($class, $method))) {
$model = new $class;
return $model->$method();
}
}
// usage
$postModel->getX('Picture');
$postModel->getY('Quote');
$postModel->getZ('Picture');
If you call a function that doesn't exist on the Post model, that magic method will be called, and it'll fire up a new instance of the model name you supply as an argument, and call the getWhatever method on it, if it exists.
It's important to note that you must not define these getters in Post, unless you want to override the methods in the other classes.
There is still the problem of this creating new instances all the time, though, and to remedy this you can use a bit of dependency injection. This means that you let the Post class contains a list of other instances of classes that it wants to use in future, so you can add and remove them at will.
This is what I would consider the actual solution, with the other examples hopefully showing how I've got here (will edit to clarify things, of course).
public $models = array();
public function addModel($instance) {
$this->models[get_class($instance)] = $instance;
}
public function __call($method, $args) {
$class = $args[0];
if (array_key_exists($class, $this->models)) {
$model = $this->models[$class];
if (is_callable(array($model, $method)) {
return $model->$method();
}
}
}
// usage
$this->addModel($pictureModel);
$this->addModel($quoteModel);
$this->getX('Picture');
$this->getY('Quote');
Here, you're passing in your existing instances of models into the Post class, which then stores them in an array, keyed by the name of the class. Then, when you use the class as described in the last example, instead of creating a new instance, it will use the instance it has already stored. The benefit of this is that you might do things to your instances that you'd want reflected in the Post model.
This means that you can add as many new models as you like that need to plug into Post, and the only thing you need to do is inject them with addModel, and implement the getters on those models.
They all require you to tell the class what models to call at some point or another. Since you have an array of dependent models, why not add a way to get everything?
public function __call($method, $args) {
$class = $args[0];
if (array_key_exists($class, $this->models)) {
$model = $this->models[$class];
if (is_callable(array($model, $method)) {
return $model->$method();
}
} elseif ($class === 'all') {
// return an array containing the results of each method call on each model
return array_map(function($model) use ($method) {
if (is_callable(array($model, $method) return $model->$method();
}, $this->models);
}
}
// usage
$postModel->getX('all');
Using this, you'll get an array containing the return values of each getX method on each model you added with addModel. You can create pretty powerful functions and classes that do all this stuff without you having to repeat tedious logic.
I have to mention that these examples are untested, but at the very least I hope the concept of what you can do has been made clear.
Note:
The same thing can be applied to __GET and __SET methods, too, which are used for accessing properties. It's also worth saying that there may be the slight risk of a library already using these magic methods, in which case you'll need to make the code a little more intelligent.