Asked  8 Months ago    Answers:  5   Viewed   45 times

I am designing my own MVC pattern to ease the process of creating homepages. My templating system needs my controller class to output my views. This means I have to output the file through a php function. I have been searching for some a while now and can't seem to find a solution.

How can I, through a PHP function, run a string representing some source code ("< ?", "< ?php", "? >" and so on) as php? Eval would not take my < ? signs (and I read that function is crap for some reason).

 Answers

39

You could execute the php code and collect the output like this:

ob_start();
include "template.phtml";
$out1 = ob_get_clean();

http://www.php.net/manual/de/function.ob-get-contents.php

Wednesday, March 31, 2021
 
StampyCode
answered 8 Months ago
51

Looks like you in fact don't want to run PHP from Visual Code, but instead you're trying to get PHP to work at all.

  1. add in external php file which I created now

You're using short tags and that's ok, if your configuration allows it, however I would recommend using explicit PHP tags: <?php echo "My First PHP site in VSCode."; ?>

In my index.html file I referenced my php file like:

There's the problem. You're placing PHP code in a HTML file. PHP code in HTML files won't be (at least by default) executed. Change the filename from index.html to index.php.

That should do it.

Wednesday, March 31, 2021
 
Chvanikoff
answered 8 Months ago
40

You are going in the wrong way about solving this.

Instead of each time manually making a new "Model" and then configuring it, you should create a structure that does it for you ( extremely simplified version ):

class ModelFactory
{
    protected $connection = null;
    // --- snip --

    public function __construct( $connection )
    {
        $this->connection = $connection;
    }
    // --- snip --

    public function buildMapper( $name )
    {
        $instance = new {$name}( $this->connection );
        return $instance;
    }
    // --- snip --

}

This class you would be using in index.php or bootstrap.php , or any other file you use as entry point for your application:

// at the bootstrap level
$modelFactory = new ModelFactory( new PDO(...) );

// i am assuming that you could get $controllerName 
// and $action from routing mechanism
$controller = new {$controllerName}( $modelFactory );
$controller->{$action}();

The main problem you have is actually cause by misunderstanding what Model is. In a proper MVC the Model is a layer, and not a specific class. Model layer is composed from multitude of class/instances with two major responsibilities:

  • domain business logic
  • data access and storage

The instances in first group are usually called Domain Objects or Business Objects (kinda like situation with geeks and nerds). They deal with validations, computation, different conditions, but have no clue how and where information is stored. It does not change how you make an Invoice , whether data comes from SQL, remote REST API or a screenshot of MS Word document.

Other group consists mostly of Data Mappers. They store and retrieve information from Domain Objects. This is usually where your SQL would be. But mappers do not always map directly to DB schema. In a classic many-to-many structure you might have either 1 or 2 or 3 mappers servicing the storage. Mappers usually one per each Domain Object .. but even that is not mandatory.

In a controller it would all look something like this.

public function actionFooBar()
{
    $mapper = $this->modelFactory->buildMapper( 'Book' );
    $book = $this->modelFactory->buildObject( 'Book' );
    $patron = $this->modelFactory->buildObject( 'Patron' );

    $book->setTitle('Neuromancer');
    $mapper->fetch( $book );

    $patron->setId( $_GET['uid']);

    if ( $book->isAvailable() )
    {
        $book->lendTo( $user );
    }

    $mapper->store( $book );

}

Maybe this will give you some indications for the direction in which to take it.

Some additional video materials:

  • Advanced OO Patterns (slides)
  • Global State and Singletons
  • Don't Look For Things!
Saturday, May 29, 2021
 
ioleo
answered 5 Months ago
90

one way is to use exec

http://ruby-doc.org/core/classes/Kernel.html#M005968

also `ls` or `cmd` works too (back tick)

Saturday, May 29, 2021
 
Sethunath
answered 5 Months ago
91

Edit: And just when you think you have it all figured out you realise that there is a better way. Check out http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx

Original: I am not sure that I understand your question 100%, but I assume that you want to upload a file to a url that looks something like http://{server name}/{Controller}/Upload? This would be implemented exactly like a normal file upload using web forms.

So your controller has an action named upload and looks similar to this:

//For MVC ver 2 use:
[HttpPost]
//For MVC ver 1 use:
//[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Upload()
{
    try
    {
        foreach (HttpPostedFile file in Request.Files)
        {
            //Save to a file
            file.SaveAs(Path.Combine("C:\File_Store\", Path.GetFileName(file.FileName)));

            // * OR *
            //Use file.InputStream to access the uploaded file as a stream
            byte[] buffer = new byte[1024];
            int read = file.InputStream.Read(buffer, 0, buffer.Length);
            while (read > 0)
            {
                //do stuff with the buffer
                read = file.InputStream.Read(buffer, 0, buffer.Length);
            }
        }
        return Json(new { Result = "Complete" });
    }
    catch (Exception)
    {
        return Json(new { Result = "Error" });
    }
}

In this case I am returning Json to indicate success, but you can change this to xml (or anything for that matter) if needed.

Tuesday, August 10, 2021
 
Trav L
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share