nette / php-generator

🐘 Generates neat PHP code for you. Supports new PHP 8.3 features.
https://doc.nette.org/php-generator
Other
2.11k stars 138 forks source link

Passing Array to addUse method #42

Closed ManojKiranA closed 5 years ago

ManojKiranA commented 5 years ago

I have been looking for this type of library which helps me lot to generate the code

I am Working with laravel so i have created the base example model for post

$namespace = new Nette\PhpGenerator\PhpNamespace('App\Models');

$namespace->addUse('Illuminate\Database\Eloquent\Model');
$namespace->addUse('Illuminate\Database\Eloquent\SoftDeletes');

And the generated Code is here

namespace App\Models;
--
   
   use Illuminate\Database\Eloquent\Model;
   use Illuminate\Database\Eloquent\SoftDeletes;
    
   /**
   * Class Post
   *
   * @package App\Models
   */
   class Post extends Model
   {
   use SoftDeletes;

And its working fine but i was planning to add multiple addUse statment so the code becomed bigger so IT WILL BE FINE IF THE addUse method accepts the array

$namespace->addUse(
[
'Illuminate\Database\Eloquent\SoftDeletes',
'Illuminate\Database\Eloquent\Model',
]
);
dg commented 5 years ago

It might be possible to add a method addUses, but I am dealing with these cases in PHP in a general way array_map([$namespace, 'addUse'], $array).

(btw in version < 2.6, this also worked array_map($namespace->addUse, $array), but it was deprecated. Perhaps it would not be bad ideat to come it back...)

JanTvrdik commented 5 years ago

The current signature is more type-safe. You can always use foreach if you want to add multiple use statements from array.

ManojKiranA commented 5 years ago

Ok Thanks for the reply

And in the recent times as of php 7

namespace App\Models;
--

   use Illuminate\Database\Eloquent\Model;
   use Illuminate\Database\Eloquent\SoftDeletes;

   /**
   * Class Post
   *
   * @package App\Models
   */
   class Post extends Model
   {
   use SoftDeletes;

Can also be written as

namespace App\Models;
--

use Illuminate\Database\Eloquent\{ Model, SoftDeletes};

   /**
   * Class Post
   *
   * @package App\Models
   */
   class Post extends Model
   {
   use SoftDeletes;

use Illuminate\Database\Eloquent{ Model, SoftDeletes};

dg commented 5 years ago

@ManojKiranA ad grouped use statements, there is a testing branch https://github.com/nette/php-generator/tree/grouped-uses

ManojKiranA commented 5 years ago

can you be more specific or share some code

dg commented 5 years ago

There is commit that implements grouped uses https://github.com/nette/php-generator/commit/7d49e177def6dd61b7e1d87c47123719ec8743d8