Search code examples
phpoopslimslim-3

PHP setting variable inside function's function


I need advice with setting variables. Im using Slim Framework. Ive got few classes.

MailboxManager.php

    public function getMailById($id) {
        /* @var $sql PDOStatement */
        $sql = $this->database->prepare("SELECT * FROM appmail_mails WHERE id = :id");
    $sql->bindParam('id', $id);
    $sql->execute();
    $record = $sql->fetch(PDO::FETCH_ASSOC);
    if ($record === false) {
        return null;
    }
    $mail = new Mail($id);
    $mail->setMailContent($record['content']);
    $mail->setMailDate($record['date']);
    $mail->setMailSubject($record['subject']);
    $mail->setMailSize($record['
return $mail;

MailController.php

class MailController
private $id;
public function showMail()
    $mail = ServicesFactory::getMailboxManager()->getMailById($this->id);
    echo "<pre>";
    var_dump($mail);

Now I want to create path with Slim Framework. In index php I put:

$app->get('/dupa/{id}', function(ServerRequestInterface $request){

    $id = $request->getAttribute('id');
    echo $id;
    $new = new MailController();
    $test = $new->showMail();
    var_dump($test);
});

How am I supposed to set id for:

$mail = ServicesFactory::getMailboxManager()->getMailById($this->id);

to properly get it? Everytime I'm trying to:

$test = $new->showMail($id)

I just get null.

Thanks for you help.


Solution

  • The route params are passed as the third argument to your closure

    $app->get('/dupa/{id}', function(ServerRequestInterface $request, $response, $args){
    
        $id = $args['id'];
        echo $id;
        $new = new MailController();
        $test = $new->showMail();
        var_dump($test);
    });