PHP code example of free2one / php-accessor

1. Go to this page and download the library: Download free2one/php-accessor library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

free2one / php-accessor example snippets



namespace App;

use PhpAccessor\Attribute\Data;

#[Data]
class Entity
{
    private int $id;

    private string $name;
}




namespace App;

use PhpAccessor\Attribute\Data;
use PhpAccessor\Attribute\Map\NamingConvention;

#[Data(namingConvention: NamingConvention::UPPER_CAMEL_CASE, accessorType: AccessorType::GETTER)]
class Entity
{
    private int $id;

    private string $name;
}



namespace App;

use PhpAccessor\Attribute\Data;
use PhpAccessor\Attribute\Overlook;

#[Data]
class Entity
{
    private int $id;

    #[Overlook]
    private string $ignore;
}



namespace App;

use PhpAccessor\Attribute\Data;
use PhpAccessor\Attribute\DefaultNull;

#[Data]
class Entity
{
    private int $id;

    #[DefaultNull]
    private string $defaultNull;
}

$entity = new Entity();
var_dump($entity->getDefaultNull());  // output: NULL



namespace App;

use PhpAccessor\Attribute\Data;
use PhpAccessor\Attribute\Overlook;

#[Data()]
class Entity
{
    #[Overlook]
    private string $ignore;

    private int $id;
}



pp\Entity;
use Composer\Autoload\ClassLoader;
use PhpAccessor\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Finder\Finder;

$scanDir = ['PROJECT_ROOT_PATH/app']; //需要扫描的项目目录
$proxyDir = 'PROJECT_ROOT_PATH/.php-accessor'; //代理类存放目录

//生成代理类
$input = new ArrayInput([
    'command' => 'generate',
    'path' => $scanDir,
    '--dir' => $proxyDir,
    '--gen-meta' => 'yes',  //发布线上时,可设置为no
    '--gen-proxy' => 'yes',
]);
$app = new Application();
$app->setAutoExit(false);
$app->run($input);

//利用composer注册自动加载
$finder = new Finder();
$finder->files()->name('*.php')->in($proxyDir);
$classLoader = new ClassLoader();
$classMap = [];
foreach ($finder->getIterator() as $value) {
    $classname = str_replace('@', '\\', $value->getBasename('.' . $value->getExtension()));
    $classname = substr($classname, 1);
    $classMap[$classname] = $value->getRealPath();
}
$classLoader->addClassMap($classMap);
$classLoader->register(true);

//Entity已被替换为代理类😸
$entity = new Entity();
$entity->setId(222);
var_dump($entity);
json
{
  "scripts":{
    "php-accessor": "@php vendor/bin/php-accessor generate"
  }
}
console
composer run-script php-accessor CLASS_PATH