I want to create a unique id, so in my Controller.php
, I write this:
use Symfony\Component\Validator\Constraints\Uuid;
and later in my function:
$unique_id = $this->uuid = Uuid::uuid4();
But I get the error message:
Attempted to call an undefined method named "uuid4" of class "Symfony\Component\Validator\Constraints\Uuid".
You can use ramsey/uuid
from https://packagist.org/packages/ramsey/uuid
composer require ramsey/uuid
After the installation :
use Ramsey\Uuid\Uuid;
function generateUid()
{
return Uuid::uuid4();
}
You can check the documentation for more informations.
Only doctrine can automatically generate uuid for you when persisting objects to database. You can set it up like this in your entity.
/**
*
* @ORM\Id
* @ORM\Column(name="id", type="guid")
* @ORM\GeneratedValue(strategy="UUID")
*/
protected $id;
And this exactly is a problem sometimes, when you need the uuid immediately for further instructions in your code, but you could not persist the object at that point of time. So I made good experiences using this package:
https://packagist.org/packages/ramsey/uuid
<?php
namespace YourBundle\Controller;
use Ramsey\Uuid\Uuid;
/**
* Your controller.
*
* @Route("/whatever")
*/
class YourController extends Controller
{
/**
* @Route("/your/route", name="your_route")
*/
public function yourFunction(Request $request)
{
try {
$uuidGenerator = Uuid::uuid4();
$uuid = $uuidGenerator->toString();
} catch (\Exception $exception) {
// Do something
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With