PHP/JavaScript代码组织技巧

Tips for code organization PHP/JavaScript

本文关键字:代码 JavaScript PHP      更新时间:2023-09-26

我一直在研究代码组织技术,尤其是JavaScript,但还没有找到合适的解决方案。所以我想我在这里请求对此事的任何意见。

简介

我目前正在做一个基于自定义开发的php框架的intranet项目。

这个框架是这样工作的:

  • 文件分为多个模块。每个模块都有自己的文件夹
  • 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函数生成的,该函数最终会返回到页面。

然后,我有了何时调用Ajax JavaScript函数的具体逻辑,以及对响应数据的所有处理,并将其注入当前模块的JavaScript中的dom中。

很多时候,调用AjaxFunction的JavaScript代码是通过PHP生成的,因为它依赖于来自PHP环境的信息。比如会话信息、特定于用户的信息或与数据库相关的东西。

因此,我目前正在编写一个PHP函数,它将一个带有AjaxCall的JavaScript函数输出到PHP函数。这个JavaScript函数是由另一个JavaScript函数调用的,或者是在JavaScript Event内部调用的,这可能取决于当前的PHP环境,这就是为什么它是用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>

我真的没有一个好的概念,什么是最好的方式来组织这个代码

感谢阅读所有这些。任何输入都将受到赞赏

您只有大约100行代码,而且已经开始变得一团糟。

我建议你使用一个框架。

对于PHP,我使用过的一个从未让我失望的框架是CakePHP。它有一个巨大的社区,一个很棒的文档,甚至还有一个博客教程可以让你开始。

这里解释了它们的文件夹结构。

对于JS来说,我遇到的最聪明的框架是AngularJS。

Angular不会强制您使用文件夹结构,但如果您为控制器、视图、服务和指令创建不同的文件夹,则会更容易。