I have a project that utilised MVC where the view file is inherting $this which refers to a view class attached to the controller.
Helper classes have been attached in some of the views and are used like follows:
<?=$this->someHelper->renderSomething()?>
I was hoping to help devs and the IDE out by doing this:
/** #var SomeHelper $this->someHelper */
It's not supported, seemingly. Is there a way to achieve this?
I can only find a workaround at the moment, to declare the helper as a new variable and include a #var statement for that.
It's not possible, you are supposed to type hint the $this instead. If $this is not any concrete class you can type hint, create a fake class/interface instead which will act as a helper to the IDE:
// somewhere outside of your code base, but accessible by the IDE
// use the name of your choice
interface CodeIgniterMvc
{
/**
* #return string
*/
function renderSomething(): string;
/**
* #param array $filter Filtering conditions
* #return \Your\App\Models\User[]
*/
function getUsers(array $filter): array;
}
and in the views:
/** #var $this CodeIgniterMvc **/
Of course include in the repository so every team member can gain such benefits.
Related
Say I have a class Book which has a property on it called $chapters. In the implementation I'm working with, this property is represented by a generic helper class called Collection, which in turn contains an array of Chapter classes.
Example:
class Book {
/** #var Collection */
public $chapters;
}
class Collection {
private $items;
public function getItems(): array {
return $this->items;
}
}
class Chapter {}
Is it possible to annotate the $chapters property in Book so that my IDE knows that it is a Collection object, but that a call to that collection's getItems() method will return an array of Chapter instances?
Can I do this without creating a child class of Collection and annotating that?
EDIT: I don't think I was clear in my goal. I'm looking to type hint a class which is outside of the Book class and give guidance on what it's $items property would be — something like this (which I'm sure is invalid):
class Book {
/**
* #var Collection {
* #property Chapter[] $items
* }
*/
public $chapters;
}
For anyone who is still looking how to solve this issue, here is the solution based on Psalm's article "Templating".
Generics (templating)
If you you are working with variable data type inside a class (or even function), you can use what is called generic data types (in PHP this might be called templating). You can use generic data types for situations, when you need to write a piece of code, which doesn't really care of the type it uses, but it might be important for the client/user of the code. In other words: you want let the user of your code (Collection) specify the type inside your structure without modifying the structure directly. The best example (which is conveniently the anwswer itself) are collections.
Collections don't really need to know about what type of data they hold. But for user such as yourself this information is important. For this reason we can create generic data type inside your Collection and everytime someone wants to use the class they can specify through the generic type the type they want the Collection to hold.
/**
* #template T
*/
class Collection
{
/**
* #var T[]
*/
private $items;
/**
* #return T[]
*/
public function getItems(): array
{
return $this->items;
}
}
Here we defined our generic type called T, which can be specified by the user of Collection such as follows:
class Book
{
/**
* #var Collection<Chapter>
*/
public $chapters;
}
This way our IDEs (or static analyzers) will recognize the generic data type inside Collection as Chapter (i.e. the T type becomes Book).
Disclaimer
Although this is the way to write generic types in PHP (at least for now), in my experience many IDEs struggle to resolve the generic type. But luckily analyzers such as PHPStan knows how to work with generics.
This is a question about the autocompletion behavior in PhpStorm (and possibly other IDEs) in conjunction with PHP docblocks.
I have to groups of classes in my application. First there are individual classes for various products (CarProduct, FoodProduct etc.), all inheriting from BaseProduct, and the counterpart for individual contracts (CarContract, FoodContract etc.), all inheriting from BaseContract.
<?php
class BaseContract
{
/** #var BaseProduct */
private $product;
/**
* #return BaseProduct
*/
public function getProduct()
{
return $this->product;
}
}
Now I have an instance of CarContract, and I wanna get some CarProduct specific information:
<?php
/* PhpStorm thinks, this is BaseProduct */
$product = $carContract->getProduct();
/* hence, getSpeed() is not available for PhpStorm */
$product->getSpeed();
The autocompletion is not working as I like. There are two workarounds for this, but both are not nice:
Overload getProduct() in the subclass, just with updated #return docblocks
Add /** #var CarProduct $product */ everywhere, where I access the product of a CarContract
Is there a "usual" way to solve something like this, or are my workarounds the only solutions?
PhpStorm does not really allow/does not support doing something like: have the same named class defined elsewhere and just use it as a reference for overriding definitions of real class. You can do that .. but IDE will warn with "multiple definitions of the same class" and it may introduce some weird behaviour/unexpected warnings...
Here is a ticket that ask for such feature: https://youtrack.jetbrains.com/issue/WI-851 -- watch it (star/vote/comment) to get notified on any progress.
Your options are: you can provide correct type hint locally (to local variable) using #var -- you already know it and that's first that you would think of:
<?php
/** #var \CarProduct $product */
$product = $carContract->getProduct();
$product->getSpeed();
Another possible way: instead of overriding actual method .. you can try doing the same but with #method PHPDoc -- will work with your code:
<?php
/**
* My Car Product class
*
* #method \CarProduct getProduct() Bla-bla optional description
*/
class CarContract extends BaseContract ...
Suppose I have the following PHP function:
/**
* #param string $className
* #param array $parameters
* #return mixed
*/
function getFirstObject($className, $parameters) {
// This uses a Doctrine DQl builder, but it could easily replaced
// by something else. The point is, that this function can return
// instances of many different classes, that do not necessarily
// have common signatures.
$builder = createQueryBuilder()
->select('obj')
->from($className, 'obj');
addParamClausesToBuilder($builder, $parameters, 'obj');
$objects = $builder
->getQuery()
->getResult();
return empty($objects) ? null : array_pop($objects);
}
Basically, the function always returns either an instance of the class specified with the $className parameter or null, if something went wrong. The only catch is, that I do not know the full list of classes this function can return. (at compile time)
Is it possible to get type hinting for the return type of this kind of function?
In Java, I would simply use generics to imply the return type:
static <T> T getOneObject(Class<? extends T> clazz, ParameterStorage parameters) {
...
}
I am aware of the manual type hinting, like
/** #var Foo $foo */
$foo = getOneObject('Foo', $params);
but I would like to have a solution that does not require this boilerplate line.
To elaborate: I am trying to write a wrapper around Doctrine, so that I can easily get the model entities that I want, while encapsulating all the specific usage of the ORM system. I am using PhpStorm.
** edited function to reflect my intended usage. I originally wanted to keep it clean of any specific use case to not bloat the question. Also note, that the actual wrapper is more complex, since I also incorporate model-specific implicit object relations and joins ect.
I use phpdoc #method for this purpose. For example, I create AbstractRepository class which is extend by other Repository classes. Suppose we have AbstractRepository::process(array $results) method whose return type changes according to the class that extends it.
So in sub class:
/**
* #method Car[] process(array $results)
*/
class CarRepo extends AbstractRepository {
//implementation of process() is in the parent class
}
Update 1:
You could also use phpstan/phpstan library. Which is used for static code analyses and you can use it to define generic return types:
/**
* #template T
* #param class-string<T> $className
* #param int $id
* #return T|null
*/
function findEntity(string $className, int $id)
{
// ...
}
This can now be achieved with the IntellJ (IDEA/phpStorm/webStorm) plugin DynamicReturnTypePlugin:
https://github.com/pbyrne84/DynamicReturnTypePlugin
If you use PHPStorm or VSCode (with the extension PHP Intelephense by Ben Mewburn) there is an implementation named metadata where you could specify your own type-hinting based on your code doing the magic inside. So the following should work (as it did on VSCode 1.71.2)
<?php
namespace PHPSTORM_META {
override(\getFirstObject(0), map(['' => '$0']));
}
Sorry for perhaps not the most accurate title. I'm having trouble figuring out what this would even be called.
I'm somewhat new to OOP with php, as most of my time is spent with procedural programming. In an effort to better learn these concepts, I'm taking an existing application and rewriting portions of it using OOP. The below example is how I set up the base class, and then I extended the base class into several smaller classes for easier maintainability. Below, you can see how I extended the base class to create a user class. Please note, that my class definitions are in separate files, but I have a working autoloader that automatically registers them
class EventScheduler{
function __construct(){
// set up database connections here
}
}
class User extends EventScheduler{
private function getUserProfile($username){
// return an array here representing
// details of passed username from database
}
public function getUserType($username){
return $this->getUserProfile($username)['user_type'];
}
}
What I'd like to be able to do is reference the User class from inside the base class, like this:
$eventApp = new EventScheduler();
$userType = $eventApp->User->getUserProfile("nameHere");
What I'm currently doing is this:
$eventApp = new EventScheduler();
//do some stuff here using the base class
$users = new User();
$userType = $users->getUserProfile("nameHere");
But as I add more child classes, I don't want to have to instantiate every extended class like I did there, I'd like to have them all grouped under the base object, rather than having each extended class in it's own object.
What you want to do is
$users = new User();
//do some stuff here using the base class
// ie $users->someFunctionFromEventScheduler();
$userType = $users->getUserProfile("nameHere");
This is a good reason to start reading up on common design patterns in OOP. There are plenty of good resources for this online and a quick google search will yield plenty of results and examples mostly hosted on github.
The specific pattern I believe you are looking for is the mediator pattern (Mediator pattern example in PHP). Rather than extending a class, as you are doing in your example, the mediator pattern is useful when you want an instance of a class that has access to many other classes that can all communicate with each other through one base class. The premise is that 'One good friend is better than many acquaintances.`.
An example for you: (interfaces are incredibly useful here as they define specific characteristics that are required in each of the classes)
/**
* Interface Mediator
*/
interface Mediator {
/**
* #param string $key
* #param Mediated $mediated
* #return void
*/
public function attach($key, Mediated $mediated);
/**
* #param $key
* #return Mediated
*/
public function getAttached($key);
}
/**
* Interface Mediated
*/
interface Mediated {
/**
* #param Mediator $mediator
* #return void
*/
public function setMediator(Mediator $mediator);
/**
* #return Mediator
*/
public function getMediator();
}
Now we need a base mediator class, I'll use your event scheduler example. Notice that it implements the Mediator interface and must, as a result implement the methods the interface requires.
/**
* Class EventScheduler
*/
class EventScheduler implements Mediator {
/**
* A collection of mediated instances.
*
* #var array
*/
protected $mediated = [];
/**
* #param string $key
* #param Mediated $mediated
* #return void
*/
public function attach($key, Mediated $mediated)
{
// So upon attaching a mediated instance we can build the two
// way binding in one place using the key as the identifier.
// First we set $this on the mediated instance.
$mediated->setMediator($this);
// Then we add this instance to our mediated array inside this instance
$this->mediated[$key] = $mediated;
}
/**
* #param $key
* #return Mediated
*/
public function getAttached($key)
{
return $this->mediated[$key];
}
}
Now we can setup a mediated instance. That can be attached to the mediator. Notice it implements the Mediated interface.
/**
* Class User
*/
class User implements Mediated {
/**
* #var Mediator
*/
protected $mediator;
/**
* #param Mediator $mediator
* #return void
*/
public function setMediator(Mediator $mediator)
{
$this->mediator = $mediator;
}
/**
* #return Mediator
*/
public function getMediator()
{
return $this->mediator;
}
}
You can create as many of the mediated instances as you like and attach them to the Mediator instance. Bear in mind that this isn't a specific mediator, in that many instances can be attached, in most cases it's better to be explicit with which classes can be attached rather than allowing dynamic registration by a key.
$scheduler = new EventScheduler();
$user = new User();
$scheduler->attach('user', $user);
// Now we know that we can get the mediator from the User class
$user->getMediator();
// We can also get the User from the mediator itself.
$scheduler->getAttached('user');
As you attach more classes you'll notice that each of them can use their mediator to get instances of the other attached classes, this is where the concept of one good friend comes from.
This is just an example and not fully featured for brevity, but should give you a good idea why using common design patterns will help you enormously and is a very good place to start when learning OOP if you want to develop good habits.
Does anyone know if PHPStorm has some builtin support for view helper autocompletion or a possibility to write a plugin for it.
I don't want to use inline var definitions for this as this would be cumbersome to do if I use a lot of view helpers
$this->inlineScript()-> //I want some autocomplete here.
$this->translate('some translation')-> //Please give me autocompletion
If I use var definitions it will end up as something like this, but it will really clutter up my view:
/* #var $inlineScript \Zend\View\Helper\InlineScript */
$inlineScript = $this->inlineScript();
$inlineScript-> //Now I have autocompletion goodness
/* #var $translate \Zend\I18n\View\Helper\Translate */
$translate = $this->translate();
$translate('some translation')-> //Now I have autocompletion goodness
NOTE I'm posting my method discussed in the comments as answer.
To typehint non-existing methods, the syntax is as following:
/**
* #method \Zend\Mvc\Controller\Plugin\Url url(string $route = null, array $params = null)
*/
class MyClass
{
}
This allows us to use have a type-hint for method url on any variable recognized as MyClass:
/* #var $a \MyClass */
$a->// typehint!
You need such a "fake" class and then start your view scripts with:
/* #var $this \MyFakeClass */
That will give you type-hints on $this within your view script.
You could ideally open a pull request against https://github.com/zendframework/zf2 with something similar to https://github.com/zendframework/zf2/pull/3438