Convert Figma logo to code with AI

laminas logolaminas-code

Extensions to the PHP Reflection API, static code scanning, and code generation

1,841
79
1,841
28

Top Related Projects

A PHP parser written in PHP

Annotations Docblock Parser

:crystal_ball: Better Reflection is a reflection API that aims to improve and provide more features than PHP's built-in reflection API.

Quick Overview

Laminas-code is a PHP library that provides tools for generating, analyzing, and manipulating PHP code. It offers functionality for creating classes, methods, and properties dynamically, as well as parsing and reflecting on existing code structures. This library is part of the Laminas Project, which is a continuation of the Zend Framework.

Pros

  • Powerful code generation capabilities for creating classes, methods, and properties programmatically
  • Robust reflection API for analyzing existing code structures
  • Integrates well with other Laminas components and frameworks
  • Actively maintained and part of a larger ecosystem

Cons

  • Steeper learning curve compared to simpler code generation libraries
  • Documentation could be more comprehensive and include more examples
  • May be overkill for small projects or simple code generation tasks
  • Requires PHP 7.4 or later, which might not be suitable for older projects

Code Examples

  1. Generating a new class:
use Laminas\Code\Generator\ClassGenerator;

$class = new ClassGenerator('MyClass');
$class->setNamespaceName('MyNamespace')
      ->addProperty('myProperty', 'defaultValue')
      ->addMethod('myMethod', ['param1', 'param2'], 'public', 'return "Hello World";');

echo $class->generate();
  1. Reflecting on an existing class:
use Laminas\Code\Reflection\ClassReflection;

$reflection = new ClassReflection('MyNamespace\MyClass');
$methods = $reflection->getMethods();

foreach ($methods as $method) {
    echo $method->getName() . "\n";
}
  1. Adding a method to an existing class:
use Laminas\Code\Generator\ClassGenerator;
use Laminas\Code\Generator\MethodGenerator;

$class = ClassGenerator::fromReflection(
    new \ReflectionClass('MyNamespace\MyClass')
);

$newMethod = new MethodGenerator('newMethod');
$newMethod->setBody('return "New method added";');

$class->addMethodFromGenerator($newMethod);

echo $class->generate();

Getting Started

To use laminas-code in your project, first install it via Composer:

composer require laminas/laminas-code

Then, you can start using it in your PHP code:

use Laminas\Code\Generator\ClassGenerator;

$class = new ClassGenerator('MyClass');
$class->addProperty('myProperty', 'defaultValue');
$class->addMethod('myMethod', [], 'public', 'return "Hello World";');

file_put_contents('MyClass.php', "<?php\n" . $class->generate());

This will generate a new PHP file named MyClass.php with the generated class code.

Competitor Comparisons

Pros of zend-code

  • Established legacy codebase with a long history of development and use
  • Extensive documentation and community resources available
  • Familiar to developers who have worked with Zend Framework

Cons of zend-code

  • No longer actively maintained, as development has shifted to laminas-code
  • May lack support for newer PHP versions and features
  • Potential security vulnerabilities due to lack of updates

Code Comparison

zend-code:

use Zend\Code\Generator\ClassGenerator;

$class = new ClassGenerator();
$class->setName('MyClass')
      ->setNamespaceName('MyNamespace');

laminas-code:

use Laminas\Code\Generator\ClassGenerator;

$class = new ClassGenerator();
$class->setName('MyClass')
      ->setNamespaceName('MyNamespace');

The code usage is nearly identical, with the main difference being the namespace change from Zend\Code to Laminas\Code. This similarity allows for easy migration between the two libraries.

laminas-code is the successor to zend-code, maintaining compatibility while providing ongoing development and support. It offers improved PHP version compatibility, regular updates, and active maintenance. Developers familiar with zend-code can easily transition to laminas-code due to the similar API and functionality.

A PHP parser written in PHP

Pros of PHP-Parser

  • More comprehensive parsing capabilities, supporting full PHP syntax
  • Actively maintained with frequent updates and improvements
  • Extensive documentation and examples for various use cases

Cons of PHP-Parser

  • Steeper learning curve due to its complexity
  • Potentially slower performance for simple code generation tasks
  • Larger codebase and dependencies

Code Comparison

PHP-Parser (parsing PHP code):

$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
$ast = $parser->parse('<?php echo "Hello World!";');

Laminas-Code (generating PHP code):

$method = new MethodGenerator();
$method->setName('sayHello')
       ->setBody('echo "Hello World!";');

Key Differences

  • PHP-Parser focuses on parsing and analyzing existing PHP code
  • Laminas-Code is primarily designed for code generation and manipulation
  • PHP-Parser provides a more detailed Abstract Syntax Tree (AST)
  • Laminas-Code offers simpler APIs for common code generation tasks

Use Cases

  • Choose PHP-Parser for advanced static analysis, code transformation, or building development tools
  • Opt for Laminas-Code when generating simple PHP classes, methods, or properties dynamically

Both libraries have their strengths, and the choice depends on the specific requirements of your project. PHP-Parser is more suitable for complex parsing tasks, while Laminas-Code excels in straightforward code generation scenarios.

Pros of ReflectionDocBlock

  • Specialized focus on parsing and manipulating DocBlocks
  • More comprehensive DocBlock parsing capabilities
  • Easier to use for projects primarily dealing with DocBlock manipulation

Cons of ReflectionDocBlock

  • Limited scope compared to laminas-code's broader functionality
  • May require additional dependencies for more complex reflection tasks
  • Less actively maintained (fewer recent updates)

Code Comparison

ReflectionDocBlock:

$factory = \phpDocumentor\Reflection\DocBlockFactory::createInstance();
$docBlock = $factory->create('/** @var string $foo */');
$tags = $docBlock->getTagsByName('var');

laminas-code:

use Laminas\Code\Reflection\DocBlockReflection;

$docBlock = new DocBlockReflection('/** @var string $foo */');
$tags = $docBlock->getTags('var');

Both libraries provide ways to parse and interact with DocBlocks, but ReflectionDocBlock offers a more specialized and comprehensive approach for DocBlock manipulation. laminas-code, on the other hand, provides a broader set of tools for code generation, reflection, and analysis beyond just DocBlocks.

ReflectionDocBlock is ideal for projects focused specifically on DocBlock parsing and manipulation, while laminas-code is better suited for more general-purpose code introspection and generation tasks. The choice between the two depends on the specific requirements of your project and the breadth of functionality needed.

Annotations Docblock Parser

Pros of Annotations

  • More lightweight and focused specifically on annotations
  • Easier to use for simple annotation parsing tasks
  • Better integration with other Doctrine projects

Cons of Annotations

  • Less flexible for general code generation tasks
  • More limited in scope compared to Laminas Code's broader capabilities
  • May require additional dependencies for advanced use cases

Code Comparison

Annotations:

/**
 * @Entity
 * @Table(name="users")
 */
class User
{
    /** @Id @Column(type="integer") */
    private $id;
}

Laminas Code:

$class = new ClassGenerator('User');
$class->addProperty('id', null, [
    'visibility' => 'private'
]);
$class->addMethod('getId');

Key Differences

  • Annotations focuses on declarative metadata using docblocks
  • Laminas Code provides programmatic code generation and manipulation
  • Annotations is more suited for ORM and framework integrations
  • Laminas Code offers broader capabilities for general-purpose code generation

Use Cases

  • Choose Annotations for Doctrine ORM, Symfony, or other annotation-heavy frameworks
  • Opt for Laminas Code for more complex code generation tasks or when working with Laminas/Zend Framework projects

Community and Maintenance

  • Both projects are actively maintained and have strong community support
  • Annotations has a larger user base due to its integration with popular frameworks
  • Laminas Code benefits from the broader Laminas ecosystem

:crystal_ball: Better Reflection is a reflection API that aims to improve and provide more features than PHP's built-in reflection API.

Pros of BetterReflection

  • More comprehensive reflection capabilities, including parsing and analyzing code without loading it
  • Ability to reflect on code that cannot be loaded into memory
  • Support for analyzing code from strings or files, not just loaded classes

Cons of BetterReflection

  • Potentially slower performance due to more complex analysis
  • Larger library size and more dependencies
  • Steeper learning curve for developers familiar with PHP's native reflection

Code Comparison

BetterReflection:

$reflector = new \Roave\BetterReflection\Reflector\DefaultReflector(
    new \Roave\BetterReflection\SourceLocator\Type\StringSourceLocator(
        '<?php class MyClass {}'
    )
);
$classInfo = $reflector->reflectClass('MyClass');

laminas-code:

$classReflection = new \Laminas\Code\Reflection\ClassReflection('MyClass');
$methods = $classReflection->getMethods();

BetterReflection offers more advanced capabilities for code analysis, particularly for unloaded code, but comes with increased complexity. laminas-code provides a simpler API that closely mirrors PHP's native reflection, making it easier to use for basic reflection tasks. The choice between the two depends on the specific requirements of your project and the depth of reflection needed.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

laminas-code

Continuous Integration Type Coverage

🇷🇺 Русским гражданам

Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.

У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.

Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"

🇺🇸 To Citizens of Russia

We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.

One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.

You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

Laminas\Code\Generator provides facilities to generate arbitrary code using an object-oriented interface, both to create new code as well as to update existing code. While the current implementation is limited to generating PHP code, you can easily extend the base class in order to provide code generation for other tasks: JavaScript, configuration files, apache vhosts, etc.