Creating various entities is a fairly common task, and requires manual fixing of type hinting.
Code like this is very common.
or
In either case, a stringy identifier is being used and the full type is repeated again before/after. phpstorm's metadata can sometimes help, but not in all cases.
There is however a better way, but requires some tweaks to the
Suppose there was a static function
A static method could be added to the
Code like this is very common.
PHP:
/** @var \XF\Entity\Phrase $phrase */
$phrase = $this->_em->create('XF:Phrase');
PHP:
$phrase = $this->_em->create('XF:Phrase');
assert($phrase instanceof \XF\Entity\Phrase );
There is however a better way, but requires some tweaks to the
EntityManager::create
function call chain.Suppose there was a static function
\XF\Entity\Phrase::create()
that returned the type static
. Type analyzers will expand this to the called class name, and in php 8.0+ the static
return type does the same thing.A static method could be added to the
\XF\MVC\Entity\Entity
base class such as:
PHP:
/**
* @return static
* @noinspection PhpMissingReturnTypeInspection
* @noinspection PhpIncompatibleReturnTypeInspection
* @noinspection PhpReturnDocTypeMismatchInspection
*/
public static function create()
{
$app = \XF::app();
static $rootClass = null;
$fullClassName = $rootClass ?? $app->extension()->resolveExtendedClassToRoot(static::class);
return $app->em()->create($fullClassName);
}
EntityManager::getEntityClassName
function would need to handle the full class name, not just the short class name. But this also means you can then do \XF::em()->create(\XF\Entity\Phrase::class);
and no longer need to use the short-name concept which involves stringy pseudo classname strings.
Upvote
6