Search code examples
phpphpactiverecord

Activerecord-association: create new object (find class)


I have an model with a relation, and I want to instantiate a new object of the relations type.

Example: A person has a company, and I have a person-object: now I want to create a company-object.

The class of the companyobject is defined in the relation, so I don't think I should need to 'know' that class, but I should be able to ask the person-object to provide me with a new instance of type company? But I don't know how.

This is -I think- the same question as New model object through an association , but I'm using PHPActiveRecord, and not the ruby one.


Reason behind this: I have an abstract superclass person, and two children have their own relation with a type of company object. I need to be able to instantiate the correct class in the abstract person.

A workaround is to get it directly from the static $has_one array:

$class   = $this::$has_one[1]['class_name'];
$company = new $class;

the hardcoded number can of course be eliminated by searching for the association-name in the array, but that's still quite ugly.


If there is anyone who knows how this is implemented in Ruby, and how the phpactiverecord implementation differs, I might get some Ideas from there?


Some testing has revealed that although the "search my classname in an array" looks kinda weird, it does not have any impact on performance, and in use it is functional enough.


Solution

  • You can also use build_association() in the relationship classes.
    Simplest way to use it is through the Model's __call, i.e. if your relation is something like $person->company, then you could instantiate the company with
    $company = $person->build_company()

    Note that this will NOT also make the "connection" between your objects ($person->company will not be set).
    Alternatively, instead of build_company(), you can use create_company(), which will save a new record and link it to $person