Unseen
Unseen

Reputation: 287

PHP MVC Add to array on post

I have the below code and whenever I post a value it doesn't add it to the array. It is like it creates a new array with only the value I posted.

<?php

class Model
{
    public $task;

    public function __construct()
    {
        $this->task = array();
    }
}

class Controller
{
    public $model;

    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    public function addTask($taskToAdd)
    {
        array_push( $this->model->task, $taskToAdd);
    }
}

class View
{
    public $model;
    public $controller;

    public function __construct(Controller $controller, Model $model)
    {
        $this->controller = $controller;
        $this->model = $model;
    }

    public function drawScreen()
    {
        $htmlForm = "<!doctype HTML>";
        $htmlForm = $htmlForm . "<html><head><title>php form test</title></head>";
        $htmlForm = $htmlForm . "<body>";
        $htmlForm = $htmlForm . "<form method='POST' action='index.php'>";
        $htmlForm = $htmlForm . "<input type='text' name='newtask' />";
        $htmlForm = $htmlForm . "<input type='submit' value='Add new task' />";
        $htmlForm = $htmlForm . "</form></body></html>";

        echo $htmlForm;
    }

    public function listTasks()
    {
        print_r($this->model->task);
    }
}

    $model = new Model();

    $controller = new Controller($model);

    $view = new View($controller, $model);

if (isset($_POST['newtask'])) {
    $taskToAdd = $_POST['newtask'];
    $controller->addTask($taskToAdd);
}

echo $view->drawScreen();
echo $view->listTasks();

Not really sure what I am doing wrong here. Is array_push not the correct way? I am using xampp if it makes any difference. Any ideas what I am doing wrong?

Upvotes: 4

Views: 563

Answers (1)

user1598814
user1598814

Reputation: 732

You have to understand that each time you the user submit the form - is new execution of your php script. So - your array - is not the same array from the last time.

To do what you want - you can use Session for example.

Upvotes: 2

Related Questions