How to do post-processing to headers/buffer in Zend's MVC? - php

So, I have created a Zend application following the quick start guide (so it has layouts, and heavy usage of application.ini configurations rather that hard-coded options) with a few changes here and there, but now I want to manipulate the output given to the browser... I've googled but it seems that I don't know how to search or more importantly what to search... I want to be able to do something like:
<?php
ob_start();
echo 'Hello ';
echo 'World';
echo '!';
$buffer = ob_get_contents();
ob_end_clean();
echo my_own_function($buffer);
?>
And do some TIDY, comment/space removing, etc... I mean it isn't just that, I want to be able to do any post-processing on-the-fly. Also I wanna get my hands over the headers before are dispatched (I'm using php5.3) it is possible?
I mean which are the classes/methods that output headers and send text to the browser so it can be interpreted?
Thanks in advance.

for this purpose you can write a Zend_Controller plugin.
See the documentation here: Zend Controller Plugins.
In your particular situation, you want to hook on the dispatchLoopShutdown method.
How to write these plugins is described on the linked page.

Related

Server-sent events in PHP (without echo or print)

We have built a prototype application in PHP and JS using Server-Sent Events (single AJAX requests, multiple streamed events sent by event handlers in PHP). Essentially the PHP at some point is using echo to send data back, much like this example: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#sending_events_from_the_server i.e.
echo "event: ping\n";
However the platform we are building for (Magento) has strict coding standards that prohibit echo and print (and print_r and var_dump). Is there any way around this aside from scrapping SSE and setting up AJAX polling?
Well, I think you have 2 ways of "echoing" something in Magento.
1. Adding your PHP file to /pub
Yes, you can run you custom PHP file to "echo" whatever you want.
But you will need to place it under <magento folder>/pub/yourfile.php.
If you're using nginx you will also need to create an exception for your file. Otherwise, Magento's routing will be used.
For doing that, find something like location ~ ^/(index|get|static|errors/report|errors/404|errors/503|health_check)\.php$ { in your nginx file, and add yourfile.php there.
For example:
location ~ ^/(index|get|static|errors/report|errors/404|errors/503|health_check|yourfile)\.php$ {.
Once your file is there, it will be served under yourstore.com/yourfile.php or yourstore.com/pub/yourfile.php (in case you are wrongfully exposing the root directory).
2. The magento way - create a controller
You will need to create a module and a controller.
There are plenty of tutorials out there explaining how to create them.
Here you can find how to create the basic module's structure.
And in this other article you can see how to create different controllers with different types of return.
Magento does have strict standards as part of there PHPCS configuration that need to be adhered to before they will allow you publish a module to there market, there is not Solid fix for the issue you have mentioned regarding using echo or print in a magneto file as part of your module. however we have found a work around by leveraging phps Output Buffering.
We have successfully submitted a module using the below mentioned function and example.
You can use ob_start() and ob_end_flush() it behaves similar to how a print or echo would when interacting with the event stream. See link below for example.
Why?
The ob_flush() function outputs the contents of the topmost output buffer and then clears the buffer of the contents. The output may be caught by another output buffer or, if there are no other output buffers, sent directly to the browser ( IE. your currently open stream ).
Example:
/**
* Send Data
*
* #param string $content
*/
function sseEchoAlternative(string $content)
{
ob_start(function () use ($content) { //Expect a warning here
return $content;
});
ob_end_flush();
}
Ref: ServerSentEvents.php

How to edit the html of frontend code before output on wordpress.

It's specifically i'm developing a plugin but stuck to edit the front end html. Is there any filter or function of wordpress to edit the html of a page?
Basically, WordPress is not built in a way to allow you that. It just goes on pushing its output whenever it wants, and when any of your filters is executed it is either before any output happened (so you have nothing to modify) or after (so it is already gone away to the browser).
There is an option which you could try: using output buffering. You can start your own output buffer on init, catch it on shutdown, and use this last opportunity to modify the output.
The general outline is as follows:
add_action('init', 'ob_start');
add_action('shutdown', function () {
$html = ob_get_clean();
$hmtl = morbvel_modify_html($html);
echo $html;
});
AFAIR, WordPress already has an action on shutdown which cleans all output buffers. It is up to you to check its source code to see what priority to assign to your shutdown hook to make it work.
PS. As a WordPress user myself I wouldn't like a plugin to do something like this - I'll be afraid that your code spoils something in my awesome html output I have carefully crafted. But you may turn out as lucky as to find your faithful customers.

How to manually call MediaWiki to convert wiki text to HTML?

I have a MediaWiki installation and I'm writing a custom script that reads some database entries and produces a custom output for client.
However, the text are in wiki format, and I need to convert them to HTML. Is there some PHP API I could call -- well there must be, but what and how exactly?
What files to include and what to call?
You use the global object $wgParser to do this:
<?php
require(dirname(__FILE__) . '/includes/WebStart.php');
$output = $wgParser->parse(
"some ''wikitext''",
Title::newFromText('Some page title'),
new ParserOptions());
echo $output->getText();
?>
Although I have no idea whether doing it this way is a good practice, or whether there is some better way.
All I found is dumpHTML.php that will dump all your mediawiki ; or may be better API:Parser wiki text which tells :
If you are interested in simply getting the rendered content of a
page, you can bypass the api and simply add action=render to your url,
like so: /w/index.php?title=API:Parsing_wikitext&action=render
Once you add action=render it seems you can get the html page ; dont you think ?
hope this could help.
regards.

PHP: Printing HTML-Friendly Code?

I am wondering if there is any technique out there for making HTML code look good when printing that HTML (multiple lines) from a PHP function?
In particular, new lines and tabs. Obviously, I want the HTML tags behind-the-scenes to look good with the proper new lines and tabs. However, depending on when I call the PHP function that is printing the HTML, I might need to start the tabs at 1, 2, 3, 4, etc. I don't want to have to pass the starting tab count to the PHP function that is printing the HTML.
So, does anyone know a general-purpose way to print HTML-friendly code with PHP? Or is there a design principle that I am missing that says, "Don't print multiple HTML lines from a PHP function." ...
Thanks,
Steve
I wouldn't bother. With DOM-inspection tools like Firebug readily available, there's no point wasting time on making something designed for a computer to read look good. See this question for other people's opinions on the matter too.
Markup Cleanup
There are some wonderful codetools out there that will cleanup (ie, adjust spacing) and repair (ie, close open tags).
Tidy is one of the more popular html cleanup/repair tools. You can parse your script's output through Tidy on-the-fly using php's output buffers.
Zend Dev Zone Intro - http://devzone.zend.com/article/761
Tidy Docs in PHP Manual - http://www.php.net/manual/en/book.tidy.php
And now, a trivial example, yay!
<?php
ob_start();
echo '<div><b> messy</b> <div> <i>blarg</I></div>';
echo ' <div>code rawr!</div>';
$output = ob_get_clean();
$tidy = tidy_parse_string($output);
tidy_clean_repair($tidy);
echo $tidy;
?>
Templating System
You should be using a templating system to separate the logic (php code) and presentation (html/markup/etc) parts of your application.
Using this practice has many advantages including, among other things, making your code easier to maintain and debug.
This is a huge topic of discussion, and almost always goes into frameworks and MVC. There are thousands of resources, here are a few :P
Writing a Template System in PHP - http://www.codewalkers.com/c/a/Display-Tutorials/Writing-a-Template-System-in-PHP/
Separation of Business Logic from Presentation Logic in Web Applications - http://www.paragoncorporation.com/ArticleDetail.aspx?ArticleID=21
if you're generating valid xhtml, you can buffer your output and at the end, do that:
$dom = new DomDocument (('1.0', 'utf-8');
$dom->loadHtml (ob_get_clean ());
$dom->formatOutput = true;
echo $dom->saveXML ();
if you're using a framework you can probably make this work as a plugin or filter.
this way it's also work if you embed template into other template or use output from helper
Generating your HTML using a template system, and keeping your templates in order is a simple way of doing this
You shouldn't be printing html with php. Use php's shorthand syntax inside of a template.
<h1><?= $page_title ?></h1>
<p><?= page_content ?></p>
instead of
<?php
echo "<h1>" . $page_title . "</h1>";
echo "<p>" . $page_content . "</p>";
?>

Implementing the View in MVC or MVP (in PHP)

I've experienced first hand the extent of the horror and foot-shooting that the ugliness of PHP can cause. I'm onto my next project (you may be wondering why I'm not just switching languages but that's not why I'm here) and I've decided to try doing it right, or at least better, this time.
I've got some models defined, and I've started on a main controller. I'm at a fork in my decisions about how to implement the view. So far, the main controller can be given lists of display functions to call, and then it can spew out the whole page with one call. It looks like:
function Parse_Body()
{
foreach ($this->body_calls as $command)
{
$call = $command['call'];
if (isset($command['args'])) $call($command['args']);
else $call();
}
}
My dilemma is this:
Would it be better to have all of my display functions return the HTML they generate, so that the main controller can just echo $page; or should the display files use raw HTML outside of PHP, which gets output as soon as it's read?
With the former, the main app controller can precisely control when things get output, without just relinquishing complete control to the whim of the displays. Not to mention, all those lists of display functions to call (above) can't really be executed from a display file unless they got passed along. With the latter method, I get the benefit of doing HTML in actual HTML, instead of doing huge PHP string blocks. Plus I can just include the file to run it, instead of calling a function. So I guess with that method, a file is like a function.
Any input or advice please?
Would it be better to have all of my
display functions return the HTML they
generate, so that the main controller
can just echo $page; or should the
display files use raw HTML outside of
PHP, which gets output as soon as it's
read?
One of the advantages of php is that the processing is similar to the output:
So:
<h1> <?= $myHeading; ?> </h1>
Is more clear than:
echo "<h1>$myHeading</h1>";
An even more than:
echo heading1($myHeading); //heading1() being an hypothethical user defined function.
Based on that I consider that it is better to in the view to have HTML and and just print the appropriate dynamic fields using php.
In order to get finner control over the output you can use: ob_start as gurunu recommended.
You could of course use any of the several php MVC frameworks out there.
My prefered one, now is: Solarphp
but Zend Framework and Cakephp could help you too.
And finally if you don't want to use any framework
You could still use a pretty slim templating engine: phpSavant.
That will save you a few headaches in the development of your view.
th
You can get the benefit of both, obtaining a string of HTML while also embedding HTML within PHP code, by using the output control functions:
From the PHP manual # http://www.php.net/manual/en/ref.outcontrol.php:
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>
First buffer everything. then replace tags using a parser at end of script.
<?php
$page_buffer = '';
function p($s){
global $page_buffer;
$page_buffer .= $s;
}
$page_buffer = str_replace(
array('<$content$>','<$title$>'),
array($pagecontent,$pagetitle),
$page_buffer);
echo $page_buffer;
?>
Samstyle PHP Framework implements output buffering and View model this way
And did I mention about benefits of buffering your output in a variable before "echo-ing"? http://thephpcode.blogspot.com/2009/02/php-output-buffering.html

Categories