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-obje
I'm currently using below solution. It's an actual solution, instead of the$has_one[1]
hack I mentioned in the question. If there is a method in phpactiverecord I'm going to feel very silly exposing msyelf. But please, prove me silly so I don't need to use this solution :DI am silly. Below functionality is implemented by the create_associationname call, as answered by @Bogdan_D
\ActiveRecord\Model
class. In my case there is a class between our classes and that model that contains extra functionality like this, so I put it there.
These are the 2 functions:
public function findClassByAssociation($associationName)
has_many
,belongs_to
and has_one
) for the associationfindClassFromArray
if an association is found.$person->findClassByAssociation('company');
private function findClassFromArray($associationName,$associationArray)
Source:
/**
* Find the classname of an explicitly defined
* association (has_one, has_many, belongs_to).
* Unsure if this works for standard associations
* without specific mention of the class_name, but I suppose it doesn't!
* @todo Check if works without an explicitly set 'class_name', if not: is this even possible (namespacing?)
* @todo Support for 'through' associations.
* @param String $associationName the association you want to find the class for
* @return mixed String|false if an association is found, return the class name (with namespace!), else return false
* @see findClassFromArray
*/
public function findClassByAssociation($associationName){
//$class = $this::$has_one[1]['class_name'];
$that = get_called_class();
if(isset($that::$has_many)){
$cl = $this->findClassFromArray($associationName,$that::$has_many);
if($cl){return $cl;}
}
if(isset($that::$belongs_to)){
$cl = $this->findClassFromArray($associationName,$that::$belongs_to);
if($cl){return $cl;}
}
if(isset($that::$has_one)){
$cl = $this->findClassFromArray($associationName,$that::$has_one);
if($cl){return $cl;}
}
return false;
}
/**
* Find a class in a php-activerecord "association-array". It probably should have a specifically defined class name!
* @todo check if works without explicitly set 'class_name', and if not find it like standard
* @param String $associationName
* @param Array[] $associationArray phpactiverecord array with associations (like has_many)
* @return mixed String|false if an association is found, return the class name, else return false
* @see findClassFromArray
*/
private function findClassFromArray($associationName,$associationArray){
if(is_array($associationArray)){
foreach($associationArray as $association){
if($association['0'] === $associationName){
return $association['class_name'];
}
}
}
return false;
}