dongyuan9892 2017-07-17 09:27
浏览 44
已采纳

PHP JavaScript 101.关注点分离

Context:

I'm extremely novice in PHP & Laravel.

I've inherited an older application with quite a lot of interesting things that happen all over the code base... coupled with being new to PHP & Laravel... it all seems quite hairy at this stage. (Coming from working in Angular for about 4/5 years, I'm having to re-learn a lot)

Scenario:

Our app is mainly focused int the African space, and HAS to run on Opera-Mini. I've been told & read up online that opera mini & AJAX aren't friends at all. (This is also my first encounter with having this platform as a first class citizen)

I'd like to ask a few of PHP experts out there, about some of the general practices, and more specifically confirming/disproving my thoughts around:

  • should I worry about this
  • attempt to clean it up
  • leave as is.

About 90% of the javascript in the app resided in *.blade.php files within <script></script> tags, with blade {{ }} bindings thrown in the mix.

@section('scripts')
    @parent
    @if(config('my.whatever.something.isEnabled'))
        <script>
            // seems fine
            var fooText = "{{ $foo }}"

            // IDE will complain but is still "fine"
            var barBoolean = {{ config('my.whatever.something.booleanFlag') }}

            if(barBoolean) {
               console.log(fooText);

               // this seems dirty to me (within the context of this script tag)
               <?php trigger_analytics_click_event('ga_analytics_something') ?>
            }
        </script>
    @endif
@stop

Usage:

@include('partials._foo',
[
   'foo' => true,
   'baz' => (config('partials.baz') - $baz->things->count())
])

Questions:

  1. Is it common practice to mix these 2 paradigms to this extent in this fashion? Eg shouldn't JS reside in JS files. (I'm not saying dont use PHP & JS together... more like, how would one use them correctly?)

    • My immediate thoughts are shift more of the JS into their own correct files, thus enabling the browser to cache them, and then have more of a client side controller of sorts
    • There are obviously a lot of complexities in doing so as, the inline PHP cant live inside the JS file thus I'd need to make use of DI in some form..., and again thats a whole other story.
  2. If the above is seen as ok. PHP -> inside -> JS -> inside -> blade.php -> inside -> <script>

    Why does my IDE complain? Is there a config/setting that I'm missing to make this OK? (I know how ridiculous this sounds)

enter image description here

I've tried wrapping the above in text quotes, while it does resolve the red squiggle... it does mean that I need another level of parsing/decoding from text -> boolean/actual value.

  1. I've seen another option of either binding to the DOM. Creating hidden fields, binding to them using {{ }}, then retrieving the field value using JS, but this also seems round about? (Is it)
  • 写回答

2条回答 默认 最新

  • dou760663 2017-07-17 10:38
    关注

    Mixing PHP and JS is not a good practice. But it's often inevitable in conventional PHP applications, as you need to somehow pass the data from PHP to Javascript.

    One approach to make code look cleaner is to wrap all PHP variables in one JS variable and use it in JS code. Consider the example:

    Before:

    <script>
      // A lot of PHP inline variables. PHP & JS tightly coupled.
      func1("{{ $var1 }}");
    
      func2("{{ $var2 }}");
    
      if ("{{ $var3 }}") {
       func3();
      }
    </script>
    

    After:

    <script>
      // PHP code in a single place
      var options = {
        one: "{{ $var1 }}",
        two: "{{ $var2 }}",
        three: "{{ $var3 }}"
      }; 
    
      // JS code without PHP-inlines 
      func1(options.one);
      func2(options.two);        
      if (options.three) {
       func3();
      }      
    </script>
    

    Using this approach, JS code becomes much less coupled to PHP and you can even put it in a separate .js file and call it with options variable as a function argument:

    someFunc.js

    // JS code without PHP-inlines 
    function someFunc(options) {
      func1(options.one);
      func2(options.two);        
      if (options.three) {
       func3();
      }
    }
    

    view.blade.php:

    <script>
      // PHP code in single place
      var options = {
        one: "{{ $var1 }}",
        two: "{{ $var2 }}",
        three: "{{ $var3 }}"
      }; 
    
      someFunc(options);      
    </script>
    

    After all, it's a matter of readability and maintainability of the code that you should worry about. If some complex piece of JS code is duplicated in many templates or mixed with PHP so that it's hard to read, it's definitely worth refactoring. But if the code snippets are simple (like in your example) I wouldn't bother refactoring it until later

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab