HasAssociations trait
Phproberto\Joomla\Entity\Core\Traits\HasAssociations
Trait for entities with associations.
Index
Usage
To start using this trait you have to include in your class the line:
use Phproberto\Joomla\Entity\Core\Traits\HasAssociations;
And then include the use
statement inside the class like:
class Article extends Entity
{
use HasAssociations;
}
This trait also requires that your entity implements the loadAssociations()
method. Here is an example of how it does it for com_content article entity through JLanguageAssociations
:
/**
* Load associations from DB.
*
* @return array
*
* @codeCoverageIgnore
*/
protected function loadAssociations()
{
if (!$this->hasId())
{
return array();
}
return \JLanguageAssociations::getAssociations('com_content', '#__content', 'com_content.item', $this->id());
}
Methods
When implementing this trait you can start using following methods in your entity:
association($langTag)
Get an association by its language tag.
Parameters:
string
$langTag (required): Language tag. Examples: es-ES, en-GB, etc.
Returns:
stdClass
Throws:
\InvalidArgumentException
if association does not exist. ALWAYS use hasAssociation()
to check if an association exists before accessing to it.
Examples:
$article = Article::instance(74);
if ($article->hasAssociation('es-ES'))
{
echo 'Article `' . $article->get('title') . '` spanish association is ' . $article->association('es-ES')->id;
}
associations($reload = false)
Get entity’s language associations.
Parameters:
None
Returns:
array
Examples:
$article = Article::instance(74);
if ($article->hasAssociations())
{
echo 'Article `' . $article->get('title') . '` has ' . count($article->associations()) . ' associations';
}
associationsIds()
Get the ids of the entity’s language associations.
Parameters:
None
Returns:
array
Examples:
$article = Article::instance(74);
if ($article->hasAssociations())
{
echo 'Article `' . $article->get('title') . '` is associated with articles with ids: ' . implode(',', $article->associationsIds());
}
hasAssociation($langTag)
Check if this entity has a specific association.
Parameters:
string
$langTag (required): Language tag. Examples: es-ES, en-GB, etc.
Returns:
boolean
Examples:
$article = Article::instance(74);
if ($article->hasAssociation('es-ES'))
{
echo 'Article `' . $article->get('title') . '` has a spanish association';
}
hasAssociationById($id)
Check if this entity has a specific association.
Parameters:
integer
$id (required): Entity identifier
Returns:
boolean
Examples:
$article = Article::instance(74);
if ($article->hasAssociationById(75))
{
echo 'Article `' . $article->get('title') . '` is associated with article 75';
}
hasAssociations()
Check if this entity has associations.
Parameters:
None
Returns:
boolean
Examples:
$article = Article::instance(74);
if ($article->hasAssociations())
{
echo 'Article `' . $article->get('title') . '` has associations';
}