Hello,
i'm currently working this way:
PHP Code:
$user = new \App\Entities\User();
$user->fill($data);
$user->userID = model('UserModel')->insert($user);
if ($user->userID === false) {
return [null, model('UserModel')->errors()];
}
It would be nice if we can just this:
PHP Code:
// new Row
$user = model('UserModel')->create();
$user->fill($data);
if($user->save() === false) {
// do something with $user->getErrors();
}
// existing Row
$user = model('UserModel')->find(15);
$user->nickname = 'newnickname';
if($user->save() === false) {
// do something with $user->errors();
}
So I started the last mins creating a work'around like this:
PHP Code:
<?php
namespace App\Models;
use CodeIgniter\Model;
class WrapperModel extends Model
{
public function getPrimaryKeyField() {
return $this->primaryKey;
}
public function create() {
return new $this->returnType();
}
}
PHP Code:
<?php
namespace App\Entities;
use CodeIgniter\Entity\Entity;
use CodeIgniter\I18n\Time;
use App\Models\WrapperModel;
class WrapperEntity extends Entity
{
// Entity Handling
protected WrapperModel $model;
protected ?string $modelName = null;
public function __construct(?array $data = null)
{
parent::__construct($data);
if ($this->modelName)
$this->model = model($this->modelName);
}
public function getPrimaryKey(){
if (!$this->model) {
// todo: throw exception
return NULL;
}
$primaryKeyField = $this->model->getPrimaryKeyField();
if (array_key_exists($primaryKeyField, $this->attributes)) {
return $this->attributes[$primaryKeyField];
}
return NULL;
}
public function setPrimaryKey($id){
if (!$this->model) {
// todo: throw exception
return NULL;
}
$this->attributes[$primaryKeyField] = $id;
}
public function delete() {
if (!$this->model) {
// todo: throw exception
return NULL;
}
return $this->model->delete($this->getPrimaryKey());
}
public function save() {
if (!$this->model) {
// todo: throw exception
return NULL;
}
if ($this->getPrimaryKey()){
return $this->model->update($this);
}else{
$returnID = $this->model->insert($this);
$this->setPrimaryKey($returnID);
return $returnID;
}
}
}
Not fully tested, but is that something others would like to see in codeigniter? Then I would make a pull request.
Regards
c0mmander