2014-04-25 76 views
0

我一直在尋找特別針對JavaScript的代碼組織技術,但還沒有找到合適的解決方案。所以我想我在這裏問這個問題的任何投入。關於代碼組織的提示PHP/JavaScript

介紹

我目前工作是基於一個定製開發的PHP框架內聯網項目。

的框架是這樣的:

  • 文件被分隔成模塊。每個模塊都有自己的文件夾
  • GET參數決定哪些模塊應加載
  • 裏面一個模塊的文件夾,你可以任何你想要的
  • 文件夾結構一個模塊內部看起來像這樣基本上做到:

    [MODULEROOT] 
    --[include] 
    ----[auto] # every php script inhere gets autocincluded when the module loads 
    ----[css] # module specific css files go in here. They also get autoincluded and injected into the header tag of the generated html 
    ----[js] # module specific js files go in here. They also get autoincluded and injected into the header tag of the generated html 
    --[interface] 
    ---- class.modInterface.php # Provides an easy interface for other modules to use their functionality. 
    ---- class.modAjaxInterface.php # All AjaxCalls inside this framework go through php which does context changes (switch working directories when calling other modules etc...), generates the necessary JavaScript calls etc... (based on jQuery's $.get()) 
    ---- class.modSearch.php # Basically an interface for providing module specific search results and hooks them into the global search 
    
  • 全球AjaxInterface類看起來像這樣(簡化):

    class ModuleAjaxInterface extends LibBase{ 
    
        private static $handler_file = "";  
        private static $file_upload_handler_file = ""; 
        private static $registered_objects = array(); 
        public static function init(){ 
         // Initialization of the class. Getting all the modules interfaces and registering them etc... 
         // Setting up the handler_file base on the config 
        } 
    
        public static function create($request_params=array(), $funcname, $options=array()){ 
         // Basically builds a JavaScript CodeBlock which handles all the function calling to the right file, parameter handling and callback functionality and returns it as String 
        } 
    
    
        public static function createPeriodical($request_params=array(), $funcname, $options=array()){ 
         // Same as above but creates periodical calls to the given function 
        } 
    
    
        public static function createUploadElement($upload_target, $input="file", $options=array()){ 
         // Creates an AjaxBased uploader and returns it as String 
        } 
    
        public function getHandlerUrl($params=array()){ 
         // Returns the URL for manual AjaxCalls to a Module defined by params 
        } 
    } 
    

問題

現在,您有關於設置一個基本的想法,這裏是我的問題

我是對的JavaScript相當沉重的幾個模塊。所以有很多AjaxCalls用於自己的AjaxInterface或其他模塊的AjaxInterfaces。

這些AjaxCalls是通過一個PHP函數end生成的,並返回給頁面。

然後,我有具體的邏輯什麼時候調用Ajax JavaScript函數以及響應數據的所有處理,並將其注入到當前模塊的JavaScript中的dom中。

很多時候調用AjaxFunctions的JavaScript代碼都是通過PHP生成的,因爲它依賴於來自PHP環境的信息。像會話信息或用戶特定的信息或數據庫相關的東西。

所以我現在編寫一個PHP函數,它將一個帶有AjaxCall的JavaScript函數輸出到一個PHP函數中。這個JavaScript函數被另一個JavaScript函數調用,或者在可能依賴於當前PHP環境的JavaScript事件中調用,這就是爲什麼它是用PHP編寫的。

我希望任何人都能得到我的問題。因此,我經常會結束很多內聯JavaScript,因爲所有模塊都是在html中的內容div內呈現的。 另外我應該如何處理$(document).ready()調用?

爲了給你一個簡單的例子是如何與這個設置的工作見下面的代碼行:

裏面我們的預訂系統

facility_container.php:

<?php 
... 

include_once('facility_dropdown.php'); 
include_once('facility_calendar.php'); 
include_once('facility_javascript.php'); 

?> 

facility_javascript.php :

<script type="text/javascript"> 
<?php 
    if(!$rights->getSpecialRight('IS_FACACC', $facility_id) && $resmode==2){ 
?> 
     _flash("<h3>Information</h3><p>You don't have access to this facility.</p>", 'INFO', 0); 
<?php 
    } 
?> 

    $(document).ready(function(){ 

     function setFacilityListAndShow(html){ 
      $('#facility-list').html(html).parent().show(); 
      $('#facility-list').combobox(); 
     } 

     function setFacilityListAndHide(html){ 
      $('#facility-list').html(html).parent().show(); 
      $('#facility-list').combobox(); 
     } 

     function setFacilityList(html){ 
      $('#facility-list').html(html); 
     } 

     [...] 

     $('#facility-list').change(function(){ 
      $('form[name="facility_form"]').submit(); 
     }); 

     <?php echo ModuleAjaxInterface::create(array('intname'=>'facilities', 'funcname'=>'getFacilitiesByTid'), 'getFacilitiesByTid', array('use_callback'=>true)); ?> 
     <?php echo ModuleAjaxInterface::create(array('intname'=>'facilities', 'funcname'=>'addReservationAsArray'), 'addReservationAsArray', array('use_callback'=>true)); ?> 
     <?php echo ModuleAjaxInterface::create(array('intname'=>'facilities', 'funcname'=>'addReservationAsSeriesAsArray'), 'addReservationAsSeriesAsArray', array('use_callback'=>true)); ?> 
     <?php echo ModuleAjaxInterface::create(array('intname'=>'facilities', 'funcname'=>'addSeriesElementAsArray'), 'addSeriesElementAsArray', array('use_callback'=>true)); ?> 
     <?php echo ModuleAjaxInterface::create(array('intname'=>'facilities', 'funcname'=>'fetchEvents'), 'fetchEvents', array('use_callback'=>true)); ?> 
     <?php echo ModuleAjaxInterface::create(array('intname'=>'facilities', 'funcname'=>'removeEvent'), 'removeEvent', array('use_callback'=>true)); ?> 
     <?php echo ModuleAjaxInterface::create(array('intname'=>'facilities', 'funcname'=>'updateEvent'), 'updateEvent', array('use_callback'=>true)); ?> 

     [...] 

     function removeEventComplete(data, input_params){ 
      if(data.status == 'success'){ 
       $('#calendar').fullCalendar('removeEvents', current_event.id); 
       current_event = null; 
       resetBookingForm(); 
      } 
      _flash('<h3>'+data.title+'</h3><p>'+data.msg+'</p>', data.status, data.timeout); 
     } 

     function updateEventComplete(data, input_params){ 
      if(data.status == false){ 
       $('#submit').show(); 
       $('#calendar').fullCalendar('rerenderEvents'); // Nothing was updated. So we rerender all the events so that the reservation appears on the same place 
      }else{ 
       resetBookingForm(); 
      } 
     } 

     <?php 
      if(!empty($facility_id)){ 
     ?> 

       [...] // 1000 lines of logic 

       $('#submit').click(function(){ 
        $(this).hide(); 
        $('#delete').hide(); 
        var startdate = new Date(_parseInt($('#start-year').val()), _parseInt($('#start-month').val()-1), _parseInt($('#start-day').val()), _parseInt($('#start-hour').val()), _parseInt($('#start-minute').val()),0); 
        var enddate = new Date(_parseInt($('#start-year').val()), _parseInt($('#start-month').val()-1), _parseInt($('#start-day').val()), _parseInt($('#end-hour').val()), _parseInt($('#end-minute').val()), 0);   
        var send_notification = 0; 
        if($('#notify').is(':checked')){ 
        send_notification = 1; 
       } 

       var is_private = 0; 
       if($('#is_private').is(':checked')){ 
        is_private = 1; 
       } 

       // New Event was created so we call addReservationAsArray(); 
       if(current_event.db_id == 0){ 
        var event_type = $('input[name=type]:checked').val(); 

        if(event_type == 'single'){ 
         var new_event = { 
          'reservation': { 
           'facilityid': <?php echo $facility_id; ?>, 
           'userid': '<?php echo $session->getUser(); ?>', 
           'serid': 0, 
           'reason': $('#title').val(), 
           'begin': startdate.getTime()/1000, 
           'end': enddate.getTime()/1000, 
           'send_notification': send_notification, 
           'is_private': is_private, 
           'style': current_event.category, 
           'count': 1 
          } 
         }; 

         addReservationAsArray(new_event); 
         current_event.is_temp = false; 
       }else{ 
        [...] 
       } 
     <?php 
      }else{ 
     ?> 
       $('.combobox').combobox(); 
       $('#facility-list').siblings().find('input.ui-combobox-input').val(""); 
     <?php  
      } 
     ?> 
    }); // document.ready() END 
</script> 

我真的沒有一個好的概念組織這些代碼的最好方法是什麼。

感謝您閱讀所有這些內容。 任何輸入將不勝感激

回答

0

你只有大約100行代碼,它已經開始混亂。

我會建議你使用一個框架。

對於PHP我已經使用並且從未讓我失望的框架之一是CakePHP。 它有一個巨大的通信,一個偉大的文檔,甚至博客教程,讓你開始。

他們的文件夾結構解釋爲here

對於JS我見過的最聰明的框架是AngularJS

Angular不會強制您使用文件夾結構,但如果您要爲控制器,視圖,服務和指令創建不同的文件夾,它會更容易。

+0

感謝您的評論,但我認爲你並沒有真正解決這個問題:我不能只是使用PHP框架,因爲它意味着立即轉儲所有內容並從頭開始重新構建它。由於整個系統已有8年以上的歷史,這不是一種選擇。關於AngularJS謝謝!我會研究一下,如果那樣會讓生活更輕鬆。 – steveHimself