Redirect to a page by passing an object

Asked

Viewed 1,204 times

6

I need to pass an object to a page. For example: I wish that the moment I redirect to a particular page that will present html, that in it I could recover this object and use whatever is in it.

Someone would have an example of how to do this?

This is an example I made to try to explain better:

<?php

include_once $_SERVER['DOCUMENT_ROOT'] . '/exemplomvc/src/model/to/CadastroTO.php';
include_once $_SERVER['DOCUMENT_ROOT'] . '/exemplomvc/src/model/cadastro.php';

class CadastroController {

    private $cadastroTO;
    private $cadastro;

    public function __construct() {

        $this->cadastroTO = new CadastroTO();

        $this->inicializa();
    }

    /*
     * 
     */
    public function inicializa() {

        $codigo = (int) $_POST['codigo'];
        $nome = (String) $_POST['nome'];

        $this->cadastroTO ->setCodigo($codigo);
        $this->cadastroTO ->setNome($nome);

        $this->cadastro = new Cadastro($this->cadastroTO);    

        try {

            //variável a ser passada para a pagina.
            $dados = $this->cadastro ->consultar();

            header("Location: " . $_SERVER['DOCUMENT_ROOT'] . '/exemplomvc/index.php');

        } 
        catch(CadastroException $erro) {

           echo $erro ->getMessage();
        }
    }
}

$obj = new CadastroController();

When this class is called, it redirects to a page that will display the html, and on this page I would like to retrieve this variable "$data" that contains an instance of the class with the gets and sets.

It would be the best way to start the session variable?

  • You can use session or Hidden input if there are few values. Show the code you have already done.

  • 2

    You can do it with javascript. If you want, use JSON. If not, with php just save the data within a Session, which you will use on more than one page (or on non-consecutive pages in the future), you do not need to keep passing the data via form.

  • I added more details, including the example class to explain it better. It would be a good solution to start a session variable?

  • Look to read about Query string, I think it can help you.

  • It may sound like a stupid question, but what exactly do you mean by redirecting? Through the code, none is being done and without this information, not only is your question meaningless, but we can end up answering something that makes less sense yet.

  • Hello @Brunoaugusto At the end of Try I would like to run a header: header("Location: " . $_SERVER['DOCUMENT_ROOT'] . '/exemplomvc/index.php'); E in index.php where it was redirected I would like to retrieve the "$data" variable. The "$data" variable contains an array of objects.

  • You have two output then. Store the property object register in a session and record it immediately and only then redirect -OR- solve every problem in this method, of this class and only redirect if there is a success, after all this is one of the functions of the Try block.

  • instead of redirecting, I think I could do a include.. , so the object would be accessible in the script within "/exemplomvc/index.php".. Of course I do not know what is in this index.php... then you should evaluate... Personal opinion, I would avoid this redirection as it is.. I find it unnecessary and only consumes more requests to the server, despite being little thing, but consumes..

Show 3 more comments

1 answer

1

You can use as a meter the object to be passed, in the method that does redirect to the page and capture. I usually use a view class that I always call on the controller.

Example:

/**
 * Description of View
 *
 * @author Francisco Nascimento
 * @email [email protected]
 */
class View  extends Atributos{
    #Armazena o Conteudo html da view
    private $_Contents;

    #armazena o arquivo html,tpl,phtml

    private $_view;
    #Armazena os parametros a serem mostrados na view

    private $_parameters;

    #PASSA MESSAGE


    public function __construct($_view = NULL, $_parameters = NULL) {

        if($_view != NULL){

            $this->setView($_view);

            $this->_parameters = $_parameters;


        }
    }
        /**
       * Define qual arquivo html deve ser renderizado
       * @param string $st_view
       * @throws Exception
       */
        public function setView($view){

            if(file_exists($view)){

                $this->_view = $view;

            }else{

                $_view = PATH_INCLUDE."404.php";
                $this->setView($_view);
            }
        }

        /**
        * Retorna o nome do arquivo que deve ser renderizado
        * @return string 
        */

        public function getView(){

            return $this->_view;
        }

        /**
        * Define os dados que devem ser repassados é view
        * @param Array $v_params
        */
        public function setParameters(array $_parameters){

            $this->_parameters = $_parameters;

        }

        /**
        * Pega os dados que foram passados como parametro para a pagina
        * @return Array
        */

        public function getParameters(){


            return $this->_parameters;
        }

        /**
        * Retorna uma string contendo todo 
        * o conteudo do arquivo de visualização
        * 
        * @return string
        */

        public function getContents(){

           ob_start();


           if(isset($this->_view)){

                require_once($this->_view);


           }

           $this->_Contents = ob_get_contents();

           ob_end_clean();

           return $this->_Contents;
        }

         /**
         * Imprime o arquivo de visualização
         */

         public function showContents()

         {
             echo $this->getContents();


         }



}

      class ListaController{

             public $_view;

             public function CompararItemAction()
             {
                 # Verifica se o usuario esta logado

                 Functions::is_logado();

                # Instancia para pegar o parametro id da url

                $app = Registry::getInstance("Application");

                # Retorna o id da url
                $id = $app->getParam('srcid');

                # Array para receber os dados dos produtos
                $produtos = array();

                # Atribui os dados dos produtos e dos mercados no array

                $produtos['Produtos'] = $this->getProdutosLista($id);
                $produtos['mercados'] = $this->getMercados();



                /* $produtos é um array de objetos passado como parametro
                   no meu caso ja tenho um netodo para capturar os dados
                   atribuidos para $produtos a idéia é mostrar como passar o parametro
                   para a view

                   a classe View recebe dois parametros, a pagina a ser mostrada e os parametros a ser exibido na pagina
                */
                # Chama a pagina Correspondente

                $this->_view = new View(PATH_VIEW . "Lista_CompararItem.phtml",$produtos);
                $this->_view->showContents();

         }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.