Level 56
Trait is just for "copy pasting" code. Injection is way more than that. For example you can inject an interface and change the implementation as you want.
I'm trying to work out when I should use a trait and when I should inject a class through the constructor.
Which is the preferred way to use service classes? The example I give is stripped down to get a feel for the problem without pasting too much code in the OP.
Solution A: Use the IoC container to inject an instance of the service layer class
class ActivationKeyGeneratorService {
public function generateKeyForUser(Release $release, User $user)
{
$randomHash = substr(md5(uniqid(mt_rand(), true)), 0, 8);
return ActivationKey::create([
'key' => $randomHash,
'user_id' => $user->id,
'release_id' => $release->id
]);
// Mail::send( ... )
// etc
}
}
class UserActivationKeyController {
public function __construct(ActivationKeyGeneratorService $generator) {
$this->generator = $generator;
}
public function create(User $user) {
$this->generator->generateKeyForUser($user);
}
}
Solution B: Put the logic inside a trait
trait ActivationKeyGenerator {
public function generateKeyForUser(Release $release, User $user)
{
$randomHash = substr(md5(uniqid(mt_rand(), true)), 0, 8);
return ActivationKey::create([
'key' => $randomHash,
'user_id' => $user->id,
'release_id' => $release->id
]);
// Mail::send( ... )
// etc
}
}
class UserActivationKeyController {
use ActivationKeyGeneratorTrait;
public function create(User $user) {
$this->generateKeyForUser($user);
}
}
Please or to participate in this conversation.