Как передать данные между контроллером в шаблоне MVC (PHP)

Я использую шаблон MVC, чтобы реализовать раздел на моем сайте, чтобы купить выставленные статьи. У меня, однако, большая проблема для реализации этого раздела и, в частности, для обмена данными между моими контроллерами и использования этих данных во всех представлениях.

В настоящее время я попробовал два решения для передачи этих данных между контроллерами:

  • во-первых, создать в верхней части кода моего контроллера некоторый объект из моих классов Model, который можно изменить из всей ветви коммутатора (и так из всего раздела моего контроллера). Я не могу понять, почему при переходе от вида к другому, всегда через один и тот же контроллер, мой объект сбрасывается и принимает значение NULL.
  • второе, не слишком полезное решение, - это использовать большой массив, передаваемый из представления в другое (из ветви переключателя того же контроллера в другую ветвь), через форму или, тем не менее, суперглобальные переменные.

Я покажу вам виды и код:

Первая картинка - логин-просмотр; пользователь не вошел в систему, уже указал форматы, в которых он хочет получить объект, и должен войти в систему.

http://i60.tinypic.com/2nq9rfd.jpg

Второе изображение - это вид после того, как этот пользователь вошел в систему. Все данные о пользователях и объектах получены через запрос, но мне нужно запомнить форматы, в которых пользователь хочет получать изображения!

Форматы... выбран способ оплаты и так далее.

http://i61.tinypic.com/2v2xkt3.jpg

Код..

Мой шаблон MVC состоит из одного index.php (единственной точки доступа к моему сайту), который создает экземпляр объекта класса "X"-Controller, который заполняет мой master.php.

Master.php - удобная динамическая страница, загружаемая моими контроллерами, которая объединяет все переменные и переменные объекта для составления запрошенного представления.

В частности, это код раздела для покупки:

Контроллер

(полный (относительный) url = /index.php?page=works&subpage=payment&imageID=00000001)

class WorksController
{
    public static $counter = 0;

    public function __construct(&$request, &$session)
    {
        self::$counter++;
        $this -> handle_input($request, $session);

    }

    private function handle_input(&$request, &$session)
    {
        //It create a new Album (class RaccoltaImmagini), that include all pictures (class Immagine) that have to be sell
        if(!isset($raccoltaImmagini))
        {

            $raccoltaImmagini = PicturesCollectionConstructor::buildNewCollection("AllPictures"); 

        }

        if(!isset($riepilogoOrdine))
        {
            //IT creates a new object (class Ordine) that include all infos to complete and to manage the transaction
            $riepilogoOrdine = new Ordine(null, null, null, null, null, null, null, null, null); 

        }

        if(!isset($userOBJ))
        {
            //It creates a new object that rappresent the user logged in and all the data associated (like credential, name, adress, credit card..)
            $userOBJ = new AuthenticatedUser(null, null, null, null, null, null,null, null, null, null, null, null, null, null);
        }

        switch($request["subpage"]) 
        {
            default: include("PHP/view/content-not-found.php");
                     break;

            case "payment": //This part of the Controller manage the view to select the payment method:             
                            //if the user is not logged in, the view charge the secondary form for the login
                            //else the view show a short recap about the options already selected, and the method of payments registered to choose


                            if(isset($request["imageID"]))  //Step 1 - The authenticated user has to choose the payment's method
                            {
                                if(isset($_SESSION["loggedIn"]) && $_SESSION[ "loggedIn"]) 
                                {
                                    if( isset($session["username"]) && isset($session["password"]))//User authenticated
                                    {   
                                        //It show which formats have been selected (it store an array of booleans, where array[$i] is true if the format is requested)                                          
                  $formati = $riepilogoOrdine -> getAllReservedFormats();


                                        //It initialize the object that represent the authenticated User
                                        $userOBJ = UserConstructor::buildUser($session["username"], $session["password"]); 

                                        //It initialize the object that represent the pictures that has to be sell
                                        $describedOBJ = $raccoltaImmagini -> getImagesByID($request["imageID"]);

                                        //- It update, newly, the information about the order:

                                        //-- It associates the user-id to ther order
                                        $riepilogoOrdine -> setUserID($userOBJ -> getID()); 

                                        //-- it associates the image-id to ther order
                                        $riepilogoOrdine -> setArticleID($describedOBJ -> getID());

                                        //-- it associates the partial import to ther order
                                        $riepilogoOrdine -> setTotalImport($describedOBJ -> getPrice());



                                        $style = "PHP/view/TransactionsStyle.php";
                                        $header = "PHP/view/Header.php";
                                        $loginFormContent = "PHP/view/loggedUserMenu.php";
                                        $slideshow=null;
                                        $works = "PHP/view/Works.php";
                                        $preview250="PHP/view/preview250.php";
                                        $SecondaryLoginForm = null;
                                        $summaryPayments = "PHP/view/summaryPayments.php";
                                        $ToPay = "PHP/view/ToPay.php";
                                        $footer="PHP/view/footer.php"; 


                                        include("master.php");
                                    }
                                }
                                else //Step 0 - The user is not still logged in
                                {

                                    //It initialize the object that represent the pictures that has to be sell 
                                    $describedOBJ = $raccoltaImmagini -> getImagesByID($request["imageID"]);


                                    //- It update the information about the order:

                                    //-- it associates the partial import to ther order
                                    $riepilogoOrdine -> setTotalImport($describedOBJ -> getPrice());

                                    //-- It associates to the order the formats select (obtained trough a previous submit) 
                                    if(isset($_REQUEST["formats"]))
                                    {
                                        $formats = array();
                                        $formats = $_REQUEST["formats"];


                                        if(isset($formats[0])) //online formats
                                        {
                                            $riepilogoOrdine -> setOnlineFormat(True); 
                                        }

                                        if(isset($formats[1])) //gallery1 format
                                        {
                                            $riepilogoOrdine -> setGallery1Format(True); 
                                        }

                                        if(isset($formats[2])) //gallery2 format
                                        {
                                            $riepilogoOrdine -> setGallery2Format(True);
                                        }

                                    }


                                    //It show which formats have been selected (it store an array of booleans, where array[$i] is true if the format is requested)                                          
                                    $formati = $riepilogoOrdine -> getAllReservedFormats();

                                    $style = "PHP/view/TransactionsStyle.php";
                                    $header = "PHP/view/Header.php";
                                    $loginFormContent = "PHP/view/LoginFormContent.php"; 
                                    $works = "PHP/view/Works.php";
                                    $preview250="PHP/view/preview250.php";

                                    $SecondaryLoginForm="PHP/view/SecondaryLoginFormContent.php";
                                    $ToPay = "PHP/view/ToPay.php";



                                    $footer="PHP/view/footer.php"; 
                                    include("master.php");
                                }
                            }
                            else
                            {
                                include("PHP/view/content-not-found.php");
                            }

                            break;
 [...] //other code omitted
} //swith closure

Вид

<?php $IMGid = $describedOBJ -> getID(); ?>
<!-- It contains a recap for every step of transaction -->
<div id="Riepilogo">  

<!-- It stores the information about the transaction -->
<div id="Transazione">
    <?php if(isset ($SecondaryLoginForm)) include($SecondaryLoginForm); ?> <!-- Step 0: User is not logged in -->

    <?php if(isset ($summaryPayments)) include($summaryPayments); ?> <!-- Step 1: User logged in and selection of payment's method -->

    <?php if(isset ($shipments)) include($shipments); ?> <!-- Step 2: selection of the shipment's method -->

</div>

<!-- It contains a recap about the pictures to buy -->
<div id="RiepilogoVisuale">

    <!-- close the window -->
    <button name="chiudi" type="button" id="closingButton" onclick="javascript:chiudi();">Chiudi</button>

    <!-- It contains details about the pictures -->
    <article id="descrizioneImmagine">
        <header id="TitleAuthor">
            <h1><?php echo($describedOBJ -> getTitolo());?>   by  </h1>
            <h2><?php echo($describedOBJ -> getAutore());?></h2>
        </header>

        <section id="previewImmagine">
            <img src="<?php echo($describedOBJ -> getPreview850());?>" alt="<?php echo($describedOBJ->getDescrizione());?>"> 
        </section>

        <!-- information about price, formats etc -->
        <section id="riepilogoAcquisto">
            <h1>Riepilogo acquisto:</h1>

            <div id="formatiIMG">
                <h2>Formati Selezionati</h2>
                <ul>

                    <?php
                        if(isset($formati["online"]) && $formati["online"]) 
                        {?>
                            <li><?php  echo("Formato online (High Res.)")?></li>
                    <?php }
                        if(isset($formati["gallery1"]) && $formati["gallery1"]) 
                        {?>
                            <li><?php echo("Formato galleria piccolo(90x160 cm)")?></li>
                    <?php }
                        if(isset($formati["gallery2"]) && $formati["gallery2"]) 
                        {?>
                            <li><?php echo("Formato galleria grande (100x200 cm)")?></li>
                    <?php }?>
                </ul>
            </div>

            <div id="AdditionalInfo">
                <section id="prezzo">
                    <h2>Prezzo:</h2>
                    <ul>
                        <li><?php echo($riepilogoOrdine -> getTotalImport())?>€</li>
                    </ul>
                </section>

                <section id="spedizione">
                    <h2>Metodo di spedizione:</h2>
                    <ul>
                        <li>Corriere Espresso</li>
                    </ul>
                </section>

            </div>

        </section>
    </article>
</div>

Я надеюсь, что вы могли бы помочь мне, спасибо всем за ваше терпение

РЕДАКТИРОВАТЬ: я добавил код моего index.php, который вызывает все контроллеры

  <?php 
  //include directives for all the controllers
  //code omitted


Dispatcher::dispatch($_REQUEST);

class Dispatcher
{


public static function dispatch(&$REQUEST)
{

    session_start();

    if(isset($REQUEST["page"]))
    {
        switch($REQUEST["page"]) 
        {

            default: 
                    include("PHP/view/content-not-found.php");
                    break;

            //code from other controllers omitted
            case "works": 
                    new WorksController($REQUEST, $_SESSION);
                    break;

        }

    }

}



}

  ?>

1 ответ

Решение

Я не уверен, что могло бы быть идеальным решением, но я подумал о роли массива $_SESSION для пользователя. Данные, которые я должен хранить и обмениваться между контроллерами, это данные, относящиеся только к пользователю, и необходимые для продолжения к следующему представлению... Поэтому я использовал $_SESSION["otherData"] для хранения содержимого моего сводного массива:

 //It stores the data on the server, first than write them to the Database
 $_SESSION["otherData"] = $riepilogoOrdine; 

 //where riepilogoOrdine track     
 //the information, obtained from the user, about the order
Другие вопросы по тегам