Code Completion dynamic properties and include/reqiure file

Hi,

I would like to know if it is possible to make code completion inside file which is included inside class. Let me give you an example:

I have "View.php" file.

class View {

     protected $view;

     public function __construct($view, $data) {
          $this->$view = $view;

          foreach($data as $k => $value) {
                              $this->{$k} = $value;                   
          }          
     }

     public function render() {
          require $view;
     }
}


I have "Template.tpl.php" and is it possible to make "$this" visible as reference to object because i would like to have code completion. Another issue are dynamic properties.

my template
<?php echo $this->some_value; ?>



I create view using such a code:

$view = new View("Template.tpl.php", array('some_value' => "Test"));
$view->render();


Thanks for any help.

2 comments
Comment actions Permalink

Hi there,

Use PHPDoc comment for that.

<?php /** @type View $this */ ?>
my template <?php echo $this->some_value; ?>


P.S.
Please note that IDE will highlight some_value in $this->some_value as unknwon field. And you cannot use PHPDoc comment to declare it as we did with $this (as it works for top level only -- in other words this will NOT work: /** @var string $this->some_value */). But you could downgrade severity of that inspection so it will not highlight it as serious errors but rather as minor ones (less visible).

Another solution (not sure if this is possibly in your framework): instead of creating template parameters as fields of the view instance ($this->{$k} = $value) just create them as ordinary variables and pass it in actual render and not constructor. For example:

class View {

     protected $view;

     public function __construct($view) {
          $this->$view = $view;
     }

     public function render($data) {
          echo $this->fetch($data);
     }
     
     public function fetch($data) {
          extract($data);
          ob_start();
          require $view;
          return ob_get_clean();
     }
}
$view = new View("Template.tpl.php");
$view->render(
array('some_value' => "Test")
);


This way you can use PHPDoc comment to let IDE know about those variables in the same way as we did with $this. For example:

<?php 
/** @type View $this */
/** @type string $some_value */
?>

my template <?php echo $some_value; ?>


P.S.
@type is the new @var (@var is considered deprecated in favour of @type)

0
Comment actions Permalink

Thank you for quick reply. You solution is very nice.

0

Please sign in to leave a comment.