PHP code example of tourze / user-attribute-bundle

1. Go to this page and download the library: Download tourze/user-attribute-bundle 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/ */

    

tourze / user-attribute-bundle example snippets


return [
    // ...
    Tourze\UserAttributeBundle\UserAttributeBundle::class => ['all' => true],
];

use Tourze\UserAttributeBundle\Entity\UserAttribute;
use Tourze\UserAttributeBundle\Repository\UserAttributeRepository;

// Create a new user attribute
$attribute = new UserAttribute();
$attribute->setUser($user);
$attribute->setName('preferred_language');
$attribute->setValue('en');
$attribute->setRemark('User preference for language');

$entityManager->persist($attribute);
$entityManager->flush();

// Retrieve user attributes
$repository = $entityManager->getRepository(UserAttribute::class);
$attributes = $repository->findBy(['user' => $user]);

// API response format
$apiData = $attribute->retrieveApiArray();
// Returns: ['id' => 123, 'name' => 'preferred_language', 'value' => 'en']

// Admin interface format
$adminData = $attribute->retrieveAdminArray();
// Returns: ['id' => 123, 'name' => 'preferred_language', 'value' => 'en', 'remark' => 'User preference']

// In your application
class CustomUserAttributeRepository extends UserAttributeRepository
{
    public function findAttributesByPrefix(UserInterface $user, string $prefix): array
    {
        return $this->createQueryBuilder('ua')
            ->where('ua.user = :user')
            ->andWhere('ua.name LIKE :prefix')
            ->setParameter('user', $user)
            ->setParameter('prefix', $prefix . '%')
            ->getQuery()
            ->getResult();
    }
}

// Bulk update user attributes
$qb = $entityManager->createQueryBuilder()
    ->update(UserAttribute::class, 'ua')
    ->set('ua.value', ':newValue')
    ->where('ua.user = :user')
    ->andWhere('ua.name = :name')
    ->setParameter('newValue', $newValue)
    ->setParameter('user', $user)
    ->setParameter('name', $attributeName);

$qb->getQuery()->execute();

use Doctrine\ORM\Events;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;

#[AsDoctrineListener(event: Events::prePersist)]
class UserAttributeListener
{
    public function prePersist(UserAttribute $attribute): void
    {
        // Custom logic before saving
        if ($attribute->getName() === 'sensitive_data') {
            $attribute->setValue(hash('sha256', $attribute->getValue()));
        }
    }
}
bash
php bin/console doctrine:migrations:migrate