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 } }
문제 이제 설정에 대한 기본적인 생각을 가지고
는 여기에 내가 자바 스크립트에 꽤 무거운 몇 가지 모듈이 내 문제
입니다. 따라서 AjaxInterface 나 다른 모듈의 AjaxInterface에 대한 AjaxCalls이 많이 있습니다.
이러한 AjaxCall은 페이지로 반향되는 PHP 함수 끝을 통해 생성됩니다.
그렇다면 Ajax JavaScript 함수를 호출 할 때뿐만 아니라 응답 데이터를 모두 처리하고 현재 모듈의 JavaScript에서 DOM에 주입 할 때 특정 논리가 있습니다.
AjaxFunctions를 호출하는 JavaScript 코드는 PHP 환경에서 오는 정보에 의존하기 때문에 PHP를 통해 생성됩니다. 세션 정보 또는 사용자 관련 정보 또는 데이터베이스와 관련된 정보.
그래서 현재 PHP 함수에 AjaxCall이있는 JavaScript 함수를 출력하는 PHP 함수를 작성합니다. 그리고이 JavaScript 함수는 현재의 PHP 환경에 의존 할 수있는 다른 JavaScript 함수 또는 JavaScript 이벤트에서 호출됩니다. 이것이 PHP로 작성된 이유입니다.
누구든지 내 문제가 발생하기를 바랍니다. 결과적으로 모든 모듈은 html의 내용 div 안에 렌더링되기 때문에 많은 인라인 JavaScript로 끝나는 경우가 종종 있습니다. $ (document) .ready() 호출도 어떻게 처리해야합니까?
<?php
...
include_once('facility_dropdown.php');
include_once('facility_calendar.php');
include_once('facility_javascript.php');
?>
facility_javascript.php : 우리의 예약 시스템
facility_container.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>
나는 실제로 좋은 개념이 없습니다. 이 코드를 구성하는 가장 좋은 방법은 무엇일까요?
이 모든 것을 읽어 주셔서 감사합니다. 모든 입력은 인정 될 것입니다
의견을 주셔서 감사합니다.하지만 문제가 실제로 발생하지는 않는다고 생각합니다. PHP 프레임 워크를 사용할 수없는 것은 지금 당장 모든 것을 덤프하고 처음부터 다시 빌드한다는 의미 일 것입니다. 전체 시스템이 8 세 이상이므로 옵션이 아닙니다. AngularJS에 감사드립니다! 삶이 더 쉬워지면 그걸 살펴볼 것입니다. – steveHimself