Skip to content

Commit c7c3fd4

Browse files
authored
Remove Model::{asModel, saveAs, newInstance} methods (#856)
1 parent 736d340 commit c7c3fd4

7 files changed

+13
-192
lines changed

docs/model.rst

+1-20
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ and even perform operations on multiple records (See `Persistence Actions` below
3535
$m->addCondition('expired', true);
3636

3737
$m->action('delete')->execute(); // performs mass delete, hooks are not executed
38-
38+
3939
$m->each(function () use ($m) { $m->delete(); }); // deletes each record, hooks are executed
4040

4141
When data is loaded from associated Persistence, it is automatically converted into
@@ -434,17 +434,6 @@ This introduces a new business object, which is a sub-set of User. The new class
434434
inherit all the fields, methods and actions of "User" class but will introduce one new
435435
action - `send_gift`.
436436

437-
There are some advanced techniques like "SubTypes" or class substitution,
438-
for example, this hook may be placed in the "User" class init()::
439-
440-
$this->onHookShort(Model::HOOK_AFTER_LOAD, function() {
441-
if ($this->get('purchases') > 1000) {
442-
$this->breakHook($this->asModel(VipUser::class);
443-
}
444-
});
445-
446-
See also :php:class:`Field\\SubTypeSwitch`
447-
448437

449438
Associating Model with Database
450439
===============================
@@ -498,14 +487,6 @@ Creates a duplicate of a current model and associate new copy with a specified
498487
persistence. This method is useful for moving model data from one persistence
499488
to another.
500489

501-
.. php:method:: asModel($class, $options = [])
502-
503-
Casts current model into another class. The new model class should be compatible
504-
with $this - you can do `$user->asModel(VipUser::class)` but converting `$user`
505-
into `Invoice::class` is a bad idea.
506-
507-
Although class is switched, the new model will retain current record data, replace all
508-
fields/actions and will combine conditions (avoiding identical conditions).
509490

510491
Populating Data
511492
===============

docs/persistence.rst

+5-74
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ take values of 123 and write it on top of 124?
431431

432432
Here is how::
433433

434-
$m->load(123)->duplicate(124)->replace();
434+
$m->load(123)->duplicate()->setId(124)->save();
435435

436436
Now the record 124 will be replaced with the data taken from record 123.
437437
For SQL that means calling 'replace into x'.
@@ -482,7 +482,7 @@ Start by creating a beforeSave handler for Order::
482482
if ($this->isDirty('ref')) {
483483

484484
if (
485-
$this->newInstance()
485+
(new static())
486486
->addCondition('client_id', $this->get('client_id')) // same client
487487
->addCondition($this->id_field, '!=', $this->getId()) // has another order
488488
->tryLoadBy('ref', $this->get('ref')) // with same ref
@@ -537,7 +537,7 @@ The other, more appropriate option is to re-use a vanilla Order record::
537537
function archive() {
538538
$this->save(); // just to be sure, no dirty stuff is left over
539539

540-
$archive = $this->newInstance();
540+
$archive = (new static());
541541
$archive->load($this->getId());
542542
$archive->set('is_archived', true);
543543

@@ -546,75 +546,6 @@ The other, more appropriate option is to re-use a vanilla Order record::
546546
return $archive;
547547
}
548548

549-
This method may still not work if you extend and use "ActiveOrder" as your
550-
model. In this case you should pass the class to newInstance()::
551-
552-
$archive = $this->newInstance('Order');
553-
// or
554-
$archive = $this->newInstance(new Order());
555-
// or with passing some default properties:
556-
$archive = $this->newInstance([new Order(), 'audit'=>true]);
557-
558-
559-
In this case newInstance() would just associate passed class with the
560-
persistence pretty much identical to::
561-
562-
$archive = new Order($this->persistence);
563-
564-
The use of newInstance() however requires you to load the model which is
565-
an extra database query.
566-
567-
Using Model casting and saveAs
568-
------------------------------
569-
570-
There is another method that can help with escaping the DataSet that does not
571-
involve record loading:
572-
573-
.. php:method:: asModel($class = null, $options = [])
574-
575-
Changes the class of a model, while keeping all the loaded and dirty
576-
values.
577-
578-
The above example would then work like this::
579-
580-
function archive() {
581-
$this->save(); // just to be sure, no dirty stuff is left over
582-
583-
$archive = $o->asModel('Order');
584-
$archive->set('is_archived', true);
585-
586-
$this->unload(); // active record is no longer accessible.
587-
588-
return $archive;
589-
}
590-
591-
Note that after saving 'Order' it may attempt to :ref:`load_after_save` just
592-
to ensure that stored model is a valid 'Order'.
593-
594-
.. php:method:: saveAs($class = null, $options= [])
595-
596-
Save record into the database, using a different class for a model.
597-
598-
As in my archiving example, here is how we can eliminate need of archive()
599-
method altogether::
600-
601-
$o = new ActiveOrder($db);
602-
$o->load(123);
603-
604-
$o->set('is_arhived', true)->saveAs('Order');
605-
606-
Currently the implementation of saveAs is rather trivial, but in the future
607-
versions of Agile Data you may be able to do this::
608-
609-
// MAY NOT WORK YET
610-
$o = new ActiveOrder($db);
611-
$o->load(123);
612-
613-
$o->saveAs('ArchivedOrder');
614-
615-
Of course - instead of using 'Order' you can also specify the object
616-
with `new Order()`.
617-
618549

619550
Working with Multiple Persistences
620551
==================================
@@ -659,7 +590,7 @@ application::
659590
$m = $this->sql->add(clone $class)->load($id);
660591

661592
// store into MemCache too
662-
$m = $m->withPersistence($this->mdb)->replace();
593+
$m = $m->withPersistence($this->mdb)->save();
663594
}
664595

665596
$m->onHook(Model::HOOK_BEFORE_SAVE, function($m){
@@ -697,7 +628,7 @@ cache::
697628
$m = $this->sql->add(clone $class)->load($id);
698629

699630
// store into MemCache too
700-
$m = $m->withPersistence($this->mdb)->replace();
631+
$m = $m->withPersistence($this->mdb)->save();
701632
}
702633

703634
Load the record from the SQL database and store it into $m. Next, save $m into

src/Model.php

+1-56
Original file line numberDiff line numberDiff line change
@@ -1287,23 +1287,6 @@ public function duplicate()
12871287
return $duplicate;
12881288
}
12891289

1290-
/**
1291-
* Saves the current record by using a different
1292-
* model class. This is similar to:.
1293-
*
1294-
* $m2 = $m->newInstance($class);
1295-
* $m2->load($m->getId());
1296-
* $m2->set($m->get());
1297-
* $m2->save();
1298-
*
1299-
* but will assume that both models are compatible,
1300-
* therefore will not perform any loading.
1301-
*/
1302-
public function saveAs(string $class, array $options = []): self
1303-
{
1304-
return $this->asModel($class, $options)->save();
1305-
}
1306-
13071290
/**
13081291
* Store the data into database, but will never attempt to
13091292
* reload the data. Additionally any data will be unloaded.
@@ -1327,47 +1310,9 @@ public function saveAndUnload(array $data = [])
13271310
return $this;
13281311
}
13291312

1330-
/**
1331-
* This will cast Model into another class without
1332-
* loosing state of your active record.
1333-
*/
1334-
public function asModel(string $class, array $options = []): self
1335-
{
1336-
$m = $this->newInstance($class, $options);
1337-
1338-
foreach ($this->data as $field => $value) {
1339-
if ($value !== null && $value !== $this->getField($field)->default && $field !== $this->id_field) {
1340-
// Copying only non-default value
1341-
$m->set($field, $value);
1342-
}
1343-
}
1344-
1345-
// next we need to go over fields to see if any system
1346-
// values have changed and mark them as dirty
1347-
1348-
return $m;
1349-
}
1350-
1351-
/**
1352-
* Create new model from the same base class
1353-
* as $this.
1354-
*
1355-
* @return static
1356-
*/
1357-
public function newInstance(string $class = null, array $options = [])
1358-
{
1359-
$model = (self::class)::fromSeed([$class ?? static::class], $options);
1360-
1361-
if ($this->persistence) {
1362-
return $this->persistence->add($model); // @phpstan-ignore-line
1363-
}
1364-
1365-
return $model;
1366-
}
1367-
13681313
/**
13691314
* Create new model from the same base class
1370-
* as $this. If you omit $id,then when saving
1315+
* as $this. If you omit $id then when saving
13711316
* a new record will be created with default ID.
13721317
* If you specify $id then it will be used
13731318
* to save/update your record. If set $id

tests/PersistentArrayTest.php

-22
Original file line numberDiff line numberDiff line change
@@ -54,28 +54,6 @@ public function testLoadArray()
5454
$this->assertSame('Smith', $mm->get('surname'));
5555
}
5656

57-
public function testSaveAs()
58-
{
59-
$p = new Persistence\Array_([
60-
'person' => [
61-
1 => ['name' => 'John', 'surname' => 'Smith', 'gender' => 'M'],
62-
2 => ['name' => 'Sarah', 'surname' => 'Jones', 'gender' => 'F'],
63-
],
64-
]);
65-
66-
$m = new Male($p);
67-
$m->load(1);
68-
$m->saveAs(Female::class);
69-
$m->delete();
70-
71-
$this->assertEquals([
72-
'person' => [
73-
2 => ['name' => 'Sarah', 'surname' => 'Jones', 'gender' => 'F'],
74-
3 => ['name' => 'John', 'surname' => 'Smith', 'gender' => 'F'],
75-
],
76-
], $this->getInternalPersistenceData($p));
77-
}
78-
7957
public function testSaveAndUnload()
8058
{
8159
$p = new Persistence\Array_([

tests/RandomTest.php

-14
Original file line numberDiff line numberDiff line change
@@ -480,20 +480,6 @@ public function testExport()
480480
], $m2->export(['code', 'name'], 'code'));
481481
}
482482

483-
public function testNewInstance()
484-
{
485-
// model without persistence
486-
$m = new Model(null, ['table' => 'order']);
487-
$a = $m->newInstance();
488-
$this->assertFalse(isset($a->persistence));
489-
490-
// model with persistence
491-
$db = new Persistence\Array_();
492-
$m = new Model($db, ['table' => 'order']);
493-
$a = $m->newInstance();
494-
$this->assertTrue(isset($a->persistence));
495-
}
496-
497483
public function testDuplicateSaveNew()
498484
{
499485
$this->setDb([

tests/ReferenceTest.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -98,11 +98,11 @@ public function testRefName3()
9898
$db = new Persistence\Array_();
9999
$order = new Model($db, ['table' => 'order']);
100100
$order->addRef('archive', ['model' => function ($m) {
101-
return $m->newInstance(null, ['table' => $m->table . '_archive']);
101+
return new $m(null, ['table' => $m->table . '_archive']);
102102
}]);
103103
$this->expectException(Exception::class);
104104
$order->addRef('archive', ['model' => function ($m) {
105-
return $m->newInstance(null, ['table' => $m->table . '_archive']);
105+
return new $m(null, ['table' => $m->table . '_archive']);
106106
}]);
107107
}
108108

@@ -112,7 +112,7 @@ public function testCustomRef()
112112

113113
$m = new Model($p, ['table' => 'user']);
114114
$m->addRef('archive', ['model' => function ($m) {
115-
return $m->newInstance(null, ['table' => $m->table . '_archive']);
115+
return new $m(null, ['table' => $m->table . '_archive']);
116116
}]);
117117

118118
$this->assertSame('user_archive', $m->ref('archive')->table);

tests/TypecastingTest.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public function testType()
8080
$this->assertSame([1, 2, 3], $mm->get('array'));
8181
$this->assertSame(8.202343, $mm->get('float'));
8282

83-
$m/*->duplicate()*/ ->setMulti(array_diff_key($mm->get(), ['id' => true]))->save();
83+
$m->setMulti(array_diff_key($mm->get(), ['id' => true]))->save();
8484

8585
$dbData = [
8686
'types' => [
@@ -198,7 +198,7 @@ public function testEmptyValues()
198198
$mm->save();
199199
$this->assertEquals($dbData, $this->getDb());
200200

201-
$m/*->duplicate()*/ ->setMulti(array_diff_key($mm->get(), ['id' => true]))->save();
201+
$m->setMulti(array_diff_key($mm->get(), ['id' => true]))->save();
202202

203203
$dbData['types'][2] = [
204204
'id' => 2,
@@ -293,7 +293,7 @@ public function testTypeCustom1()
293293
$this->assertTrue($mm->get('b1'));
294294
$this->assertFalse($mm->get('b2'));
295295

296-
(clone $m)/*->duplicate()*/ ->setMulti(array_diff_key($mm->get(), ['id' => true]))->save();
296+
(clone $m)->setMulti(array_diff_key($mm->get(), ['id' => true]))->save();
297297
$m->delete(1);
298298

299299
unset($dbData['types'][0]);

0 commit comments

Comments
 (0)