For convenient transfer to one of the widgets JS and html code (it is more convenient to redo JS visually), I began to use ob_start (and ob_get_clean). But it turns out that on one page, 3-4 blocks of the form are stuck:

<?ob_start();?> alert('Быдлокодить - плохо'); <?$alert = ob_get_clean(); ?> 

The example is of course greatly simplified, but it conveyed the essence. Question: Is it right? And if not, why not.

  • There are no technical problems, how bad the use of the global state is is pretty bad, but this is PHP, nuff said - Alexei Averchenko

3 answers 3

Why not? If there is no other way out.

    php == system logic

    html + js + css == view (user interface)

    These are different things and it is extremely undesirable to mix them. When the total amount of your code exceeds XXXXX lines, you yourself will not be happy.

    Read at your leisure .

    • I naturally know about the MVC model, and even try to practice the rules of the “fat model, thin controller”, but it seems I will learn everything from my own mistakes = / - slowpokewarrior

    Any tool can be used for different purposes and with different results. Look at your code - what does it look like? If it is clear and beautiful, then ob_start was used for its intended purpose. If the code in the end resembles an unreadable mess, then ob_start was redundant.

    Of course, it is quite difficult to appreciate the beauty of the code if no alternatives are visible. I'll tell you about my favorite approach.

    Any code can be divided into two parts: immutable logic and parameters. In your case, the entire code is immutable, so I will make a slight complication:

     <? $message = 'Быдлокодить - плохо' ?> <? ob_start(); ?> alert('<?=message?>'); <? $alert = ob_get_clean(); ?> 

    Now we have two parts of the code — unchangeable logic (the alert call) —and a computed parameter (the string “Byloclock is bad”).

    The immutable part is taken out in a separate file and drawn up as a function. Parameters are placed in the settings object:

     function widget_show_alert(cfg) { alert(cfg.message); } 

    Then this file will be added to the page and thus the function will be available for us - and we have to call this function in the right place, passing the parameter to it. It is inconvenient to form the “old-fashioned” settings object for PHP - and even that will break the beauty of the approach. Therefore, I will take advantage of the fact that any JSON is a valid JS literal:

     $cfg = json_encode(array('message' => 'Быдлокодить - плохо')) $alert = "widget_show_alert($cfg)"; 

    At the same time, the potential vulnerability of the "js-injection" type disappeared.

    Personally, it seems to me that the code has become more beautiful. It may seem different to you :)