Laravel Modular Request to a different Controller - php

I am using a github project named mnabialek/laravel-modular. The package works fine but I cant pass requests to a different controller in diffrent module. How can I do that.
TestModule Controller
<?php
namespace App\Modules\TestModule\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use App\Modules\TestModule\Http\Requests\TestModuleRequest;
use App\Modules\Admin\Http\Requests\AdminRequest;
use App\Modules\TestModule\Repositories\TestModuleRepository;
use App\Modules\TestModule\Services\TestModuleService;
class TestModuleController extends Controller
{
/**
* #var TestModuleRepository
*/
protected $repo;
/**
* #var TestModuleService
*/
protected $service;
/**
* TestModuleController constructor.
*
* #param TestModuleRepository $repo
* #param TestModuleService $service
*/
public function __construct(TestModuleRepository $repo, TestModuleService $service)
{
$this->repo = $repo;
$this->service = $service;
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//
//echo "Here you are";
//$data["data"] = "Here you are";
//return view("welcome")->with($data);
$working = "Its Working";
$message = App::make("App\\Modules\\Admin\\Http\\Controllers\\AdminController")->create($working);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
}
AdminController.php
<?php
namespace App\Modules\Admin\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use App\Modules\Admin\Http\Requests\AdminRequest;
use App\Modules\Admin\Repositories\AdminRepository;
use App\Modules\Admin\Services\AdminService;
class AdminController extends Controller
{
/**
* #var AdminRepository
*/
protected $repo;
/**
* #var AdminService
*/
protected $service;
/**
* AdminController constructor.
*
* #param AdminRepository $repo
* #param AdminService $service
*/
public function __construct(AdminRepository $repo, AdminService $service)
{
$this->repo = $repo;
$this->service = $service;
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create($working)
{
die(print_r($working));
//
}
}
Here is the error I am getting.
Class 'App\Modules\TestModule\Http\Controllers\App' not found

Try the following:
$message = Illuminate\Support\Facades\App::make("App\\Modules\\Admin\\Http\\Controllers\\AdminController")->create($working);
As App does not exist in the current namespace, you have to call it from where it is defined.

Related

Using a repository function in service Symofony

I am using a service within twig like this
{{ count_service.getCount(term.getId) }}
I want the service to use a repository function, repository function
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Mapping;
class SynonymRepository extends EntityRepository
{
public function getCount($termId)
{
$qbSynonymType = $this->getEntityManager()->createQueryBuilder();
$synonymTypes = $qbSynonymType->select('synonymType.id, synonymType.type')
->from('AppBundle:SynonymType', 'synonymType')
->getQuery()->getResult();
$qb = $this->getEntityManager()->createQueryBuilder();
$count = [];
$qb->select('count(synonym.synonymId)')
->from('AppBundle:Synonym','synonym');
foreach($synonymTypes as $type) {
$count[$type['type']] = $qb
->where('synonym.term = :termId')
->andWhere('synonym.synonymType = :type')
->setParameter('termId', $termId)
->setParameter('type', $type['id'])
->getQuery()->getSingleScalarResult();
}
$qbTerm = $this->getEntityManager()->createQueryBuilder()->from('AppBundle:Term', 'term');
$count['parent'] = "NaN";
$count['children'] = "NaN";
return $count;
}
}
My service.yml looks like this
synonymrepository:
class: Doctrine\ORM\EntityRepository
factory: ["#doctrine.orm.entity_manager", getRepository]
arguments:
- AppBundle\Entity\SynonymType
term_count:
class: AppBundle\Services\TermCount
arguments:
- "#synonymrepository"
And finally my service looks like this
<?php
namespace AppBundle\Services;
use AppBundle\Repository\SynonymRepository;
class TermCount
{
private $repository;
public function __construct()
{
$this->repository = new SynonymRepository();
}
public function getCount($termId)
{
return $this->repository->getCount($termId);
}
}
When running this I am getting the following error
Type error: Too few arguments to function Doctrine\ORM\EntityRepository::__construct(), 0 passed in /var/www/html/src/AppBundle/Services/TermCount.php on line 15 and exactly 2 expected
I assume this is happening because extending SynonymRepository with the EntityRepository requires EntityManagerInterface $em and Mapping\ClassMetadata $class. But I am not sure how pass them to EntityRepository.
I was using this answer to get me here, lost on how to actually implement the finall bit.
Thanks for helping.
UPDATE
Entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Table(name="synonym")
* #ORM\Entity(repositoryClass="AppBundle\Repository\SynonymRepository")
*/
class Synonym
{
/**
* #var int
* #ORM\Id()
* #ORM\Column(name="synonym_id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $synonymId;
/**
* #var Term
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Term", inversedBy="synonyms")
*/
protected $term;
/**
* #var SynonymType[]
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\SynonymType", inversedBy="synonyms")
*/
protected $synonymType;
/**
* #var int
* #ORM\Column(name="language_id", type="integer")
*/
protected $languageId;
/**
* #var string
* #ORM\Column(name="synonym", type="string", length=255)
*/
protected $synonym;
public function __construct()
{
// $this->synonymType = new ArrayCollection();
}
/**
* #return int
*/
public function getSynonymId(): int
{
return $this->synonymId;
}
/**
* #return Term
*/
public function getTerm(): Term
{
return $this->term;
}
/**
* #param int $termId
* #return Term
*/
public function setTerm(int $termId): Term
{
$this->term = $termId;
return $this->term;
}
/**
* #return SynonymType[]
*/
public function getSynonymType()
{
return $this->synonymType;
}
/**
* #param SynonymType $synonymType
* #return SynonymType
*/
public function setSynonymType(SynonymType $synonymType): SynonymType
{
$this->synonymType = $synonymType;
return $this->synonymType;
}
/**
* #return int
*/
public function getLanguageId(): int
{
return $this->languageId;
}
/**
* #param int $languageId
* #return Synonym
*/
public function setLanguageId(int $languageId): Synonym
{
$this->languageId = $languageId;
return $this;
}
/**
* #return string
*/
public function getSynonym(): string
{
return $this->synonym;
}
/**
* #param string $synonym
* #return Synonym
*/
public function setSynonym(string $synonym): Synonym
{
$this->synonym = $synonym;
return $this;
}
}
You need to use DI (Dependency injection) in your construct insted of using new cause as i see the erreur your SynonymRepository depends on other services
<?php
namespace AppBundle\Services;
use AppBundle\Repository\SynonymRepository;
class TermCount
{
private $repository;
public function __construct(SynonymRepository $synonymRepository)
{
$this->repository = $synonymRepository;
}
public function getCount($termId)
{
return $this->repository->getCount($termId);
}
}

Laravel Notification with Mailable

In my Laravel application I have a Notification that sends a Mailable when a User is deleted.
The Notification class:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use App\User;
use App\Mail\UserDeleted as UserDeletedEmail;
class UserDeleted extends Notification implements ShouldQueue
{
use Queueable;
/**
* The user instance being passed to the notification
*
* #var User $user
*/
protected $user;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail', 'database'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new UserDeletedEmail($notifiable, $this->user));
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
'user_id' => $this->user['id'],
'user_username' => $this->user['username'],
'user_email' => $this->user['email'],
'user_full_name' => $this->user['full_name'],
];
}
}
In this case $notifiable is an instance of User but soo is $user as this is the user that has been deleted.
The Mailable looks like this:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Spatie\Permission\Models\Role;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\User;
class UserDeleted extends Mailable
{
use Queueable, SerializesModels;
/**
* The order instance.
*
* #var User
*/
public $user;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this
->to($this->user->email)
->subject("{$this->user->full_name} been deleted from the Citibase Intranet")
->markdown('mail.user-deleted');
}
}
The issue is, as they're both instances of User I'm effectively passing the wrong instance in the subject line.
Everything is triggered through the UserObserver.
/**
* Handle the user "deleted" event.
*
* #param \App\User $user
* #return void
*/
public function deleted(User $user)
{
Log::notice("A user has been deleted: {$user->full_name} by " . optional(auth()->user())->full_name ?? "System");
User::role(['admin'])->get()
->each->notify(
(new UserDeleted($user))->delay(now()->addSeconds(10))
);
}
At the moment your UserDeleted mailables constructor is only accepting the user that should receive the email, you can add the other user as well and you will have access to both.
Something like this:
class UserDeleted extends Mailable
{
use Queueable, SerializesModels;
/**
* #var User
*/
public $admin;
/**
* #var User
*/
public $deletedUser;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct(User $admin, User $deletedUser)
{
$this->admin = $admin;
$this->deletedUser = $deletedUser;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this
->to($this->admin->email)
->subject("{$this->deletedUser->full_name} been deleted from the Citibase Intranet")
->markdown('mail.user-deleted');
}
}

Symfony 3 Attempted to load class "LessonRepository" from namespace "DrumLessonBookingApp\DrumLessonBookingBundle\Repository"

When trying to get the default repository class for my entity Lesson I keep getting the following error:
Attempted to load class "LessonRepository" from namespace "DrumLessonBookingApp\DrumLessonBookingBundle\Repository".
Did you forget a "use" statement for another namespace?
I use the exact same method as a User entity which works perfectly fine.
The code for my controller is:
namespace DrumLessonBookingApp\DrumLessonBookingBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use DrumLessonBookingApp\DrumLessonBookingBundle\Entity\User;
use DrumLessonBookingApp\DrumLessonBookingBundle\Entity\Lesson;
use DrumLessonBookingApp\DrumLessonBookingBundle\Repository;
class LoginController extends Controller
{
public function displayAction()
{
return $this->render('DrumLessonBookingAppDrumLessonBookingBundle:Default:login.html.twig');
}
public function processloginAction(Request $request)
{
$doctrine = $this->getDoctrine()->getManager();
$email = $request->get('email');
$pwd = $request->get('pwd');
$user = $doctrine->getRepository('DrumLessonBookingAppDrumLessonBookingBundle:User')->findOneBy(array('email' => $email,'password' => $pwd));
if($user->getAdministrator() == 1)
{
$session = $this->get('session');
$session->set('loggedin', true);
$lessons = $doctrine->getRepository('DrumLessonBookingAppDrumLessonBookingBundle:Lesson')->findAll();
return $this->render('DrumLessonBookingAppDrumLessonBookingBundle:Default:dashboard.html.twig', array("lessons" => $lessons));
}
else {
return new Response('doctrine not working');
}
}
}
I am also having difficulty to generate a custom Respository class using doctrine so tried creating one myself for the User entity but symfny doesn't pick it up or recognise the custom method. See below:
namespace DrumLessonBookingApp\DrumLessonBookingBundle\Repository;
use Doctrine\ORM\EntityRepository;
use DrumLessonBookingApp\DrumLessonBookingBundle\Entity\User;
class UserRepository extends EntityRepository
{
public function loginUser($email, $password)
{
$entityM = $this->getEntityManager();
$dql = $entityM->createQuery(
'SELECT u FROM DrumLessonBookingAppDrumLessonBookingBundle:User u
WHERE u.email = :email
AND WHERE u.password = :pwd');
$dql->setParameter('email', $email);
$dql->setParameter('pwd', $password);
$user = $query->getResult();
return $user;
}
}
I have searched similar questions but cannot find a solution, someone please help!
My Lesson Entity
namespace DrumLessonBookingApp\DrumLessonBookingBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="lessons")
* #ORM\Entity(repositoryClass="DrumLessonBookingApp\DrumLessonBookingBundle\Repository\LessonRepository")
* */
class Lesson {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* */
private $id;
/**
* #ORM\Column(type="date")
* */
private $date;
/**
* #ORM\Column(type="time")
* */
private $time;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="lessons")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* */
private $user;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set date
*
* #param \DateTime $date
*
* #return Lesson
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set time
*
* #param \DateTime $time
*
* #return Lesson
*/
public function setTime($time)
{
$this->time = $time;
return $this;
}
/**
* Get time
*
* #return \DateTime
*/
public function getTime()
{
return $this->time;
}
/**
* Set User
*
* #param object
* #return Lesson
* */
public function setUser(User $user)
{
$this->user = $user;
return $this;
}
/**
* Set User
*
*
* #return User
* */
public function getUser($user)
{
return $this->user;
}
}
There is nothing in my custom Lesson Repository but surely it should still find the methods such as findAll() etc from the entityRepository it extends
seems you have multiple questions for one answer
you need to reference the repositoryClass it in your Entity-class :
/**
* USER
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="DrumLessonBookingApp\DrumLessonBookingBundle\Repository\UserRepository")
*/
class User
{
i guess you missing the same at your Lesson Entity.
You dont have to add a "use" statement then

Laravel - only a zero is saved to the database

I have a simple car model with one attribute:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Filesystem\Filesystem;
/*
* TODO:
* Property Fotos ausfüllen
*/
class Car extends Model
{
//Tablenname
protected $table = 'cars';
protected $fillable = ['title'];
public $timestamps = false;
/**
* #var string
*/
protected $title = NULL;
/**
* #var integer
*/
protected $imagesId = NULL;
/**
*
* #return string
*/
public function getTitle()
{
return $this->attributes['title'];
}
/**
*
* #param string $title
*
* #return void
*/
public function setTitle($title)
{
$this->attributes['title'] = $title;
}
}
This is my store function from the controller:
<?php
namespace App\Http\Controllers;
use App\Car;
class CarController extends Controller
{
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$car = new Car();
// $car->setTitle($request->title);
$car->setTitle('stackoverflow');
$car->save();
...
}
}
However, this is how the entry in the database looks like:
Title is always zero! I also tried it with other models, same.
Check field datatype.if you want to store string you have to change your 'title' field datatype to varchar.
hope it works.

getServiceLocator() outside Controller

I have a class: ClassA(), i need the Doctrine Service $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');.
I try implements the interface ServiceManagerAwareInterface, but the functions, getServiceLocator() and setServiceLocator(ServiceLocatorInterface $serviceLocator) not work.
Someone used the ServiceLocator outside Controller class in ZF2? It's possible?
<?php
namespace DbSession\Service;
use Zend\Session\SaveHandler\SaveHandlerInterface;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;
/**
* Description of SessionDB
*
* #author rab
*/
class SessionDB implements SaveHandlerInterface, ServiceLocatorAwareInterface {
use ServiceLocatorAwareTrait;
/**
* Session Save Path
*
* #var string
*/
protected $sessionSavePath;
/**
* Session Name
*
* #var string
*/
protected $sessionName;
/**
* Lifetime
* #var int
*/
protected $lifetime;
/**
* Constructor
*
*/
public function __construct() {
}
/**
* Open the session
*
* #return bool
*/
public function open($savePath, $name) {
echo "open session";
}
/**
* Close the session
*
* #return bool
*/
public function close() {
echo "close session";
}
/**
* Read the session
*
* #param int session id
* #return string string of the sessoin
*/
public function read($id) {
echo "read session";
}
/**
* Write the session
*
* #param int session id
* #param string data of the session
*/
public function write($id, $data) {
$this->getServiceLocator()->get('');
echo "write";
}
/**
* Destoroy the session
*
* #param int session id
* #return bool
*/
public function destroy($id) {
echo "destroy session";
}
/**
* Garbage Collector
*
* #param int life time (sec.)
* #return bool
*/
public function gc($maxlifetime) {
echo "gc session";
}
}
The easiest way would be to use the ServiceLocatorAwareTrait (part of ZF2). If you do use that make sure your class implements ServiceLocatorAwareInterface (you don't actually have to implement it as the trait does that for you, but you do have to add it to your class' implements clause).
So you get something like this:
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorAwareTrait;
class ClassA implements ServiceLocatorAwareInterface {
use ServiceLocatorAwareTrait;
}
Then you can just call $this->getServiceLocator() to get a hold of a servicelocator instance.
However if you just need the Doctrine entitymanager it's better practice to just inject this one dependency instead of injecting the ServiceLocator.
Finally solved the problem. My class SessionDatabase() is correct. My instance was wrong.
Implements class:
class SessionDatabase implements SaveHandlerInterface, ServiceLocatorAwareInterface {
use ServiceLocatorAwareTrait;
public function write($id, $data) {
$em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
}
Instance:
private function initDbSession(MvcEvent $e) {
$serviceManager = $e->getApplication()->getServiceManager();
$saveHandler = new SessionDatabase();
$saveHandler->setServiceLocator($serviceManager);
}
Thanks everyone that helped!!! :D

Categories