我不知道你的输出需要哪些数据以及输入是什么。以下是针对输出 HTML/CSS 并与 MySQL 数据库交互的应用程序的一些粗略重构技巧。这不可能是一个完整的列表,描述只能粗略地概述一些想法:
将 CSS 移出 HTML。在链接的 CSS 定义中有效地使用选择器,并替换任何 style 属性(如果还有)。这使得您的 CSS 代码可重用并且更加模块化。它将帮助您找到 HTML 内部的缺陷,并将结构 (HTML) 与表示 (CSS) 分开。有效的 HTML 从有效使用 CSS 开始,这两者一起非常强大,通常这已经可以减轻您的程序输出例程。
将业务逻辑移出 HTML。 HTML 和您的代码都可能是庞然大物,因此最好将它们分开。他们有互相争斗的倾向,而且由于两者都非常强大,因此在您开发应用程序时,争斗将会继续,这会分散您对需要完成的工作的注意力。 考虑一下您的应用程序中是否需要已经有复杂的输出,或者您是否可以只传递带有子元素的数组(键是 var,var 可以包含字符串或数字或另一个 var 数组)。通常,将复杂的数据传递到视图或模板中都需要这些。然后,您的 HTML 只需要在子数组上回显一些数组成员和/或 foreach 。这是创建模板的非常简单的技术。您可以使用 PHP,因此实际上非常灵活(只需绘制属于您的视图层的代码以及属于应用程序的一部分的边框,例如为视图提供值)。
Do you have any suggestion on how to successfully seperate HTML/CSS from PHP/SQL?
Congrats for looking how you can improve code. That's the precondition, you need to want to improve it and the topic is lengthy. So your will is crucial.
I start lightly and then try to give some tips. As you're missing experience, look for one point to start with, most certainly the last one of the list below. But first things first:
To separate something from each other, you need to have some code that separates:
The Separator here actually is PHP code as well, but I think you get the idea.
As you can see only the Separator talks with HTML/CSS and PHP/SQL.
So both HTML/CSS and PHP/SQL need to have an interface with Separator (the line between) to make this work.
Normally in a program you pass around data that get's processed. The data is pretty dynamic and can have a compound complexity, especially if you pass data to an output routine that should format it properly.
There are multiple ways of how such a Separator (or multiple of them) can be written. You can layer your software or provide components that do things in their area or domain. E.g. you have a database layer or database component that takes care about the interaction with the database.
Or you have a templating engine that takes care to put your strings and arrays into some readable HTML.
In short this is the pasta theory of software design:
Spaghetti code - all in one, code is heavily interwoven, preferable with Bolognese or Aglio, Olio e Peperoncino.
Lasagne code - Layered, one layer has two other layers it interacts with (unless bottom or top), always with Béchamel sauce.
Tortelini code - Small components that just do their job, they have Meat or Spicy Vegetables inside.
Like we eat different pasta in our lives, when programming we need to deal with all these different type of code as well, and we develop our own preferred taste over time. As a kid we're feed but over time we start to cook something our own and vary the recipes.
So I think it's a good point you just don't want to now eat MVC Framework X with much awesome for the next weeks only because somebody told you it's the way to eat now. And before eating, there is tasting, right? Not to mention fast-food, you know like these noodles with sauce in package - only add water. Urgh.
I don't know which data your output needs and what the input is. Following are some rough refactoring tips for applications that output HTML/CSS and interact with a MySQL database. This can not be a complete list and the descriptions can only roughly outline some thoughts:
Move CSS out of HTML. Use selectors effectively in the linked CSS definition and replace any style attributes if you still have some. This makes your CSS code re-useable and more modular. It will help you to find flaws inside your HTML and to separate the Structure (HTML) from the Presentation (CSS). Effective HTML start with effective usage of CSS, those two are very powerful together and often this already will lighten your programs output routines.
Move business logic out of HTML. Both HTML and your code can be a beast, so better keep them apart. They have the tendency to fight with each other, and as both are very powerful, the fight will continue while you develop your application, that distracts you from the work you need to do. Consider if you need to already have complex output inside your application or if you can just pass on arrays with subelements (a key is a var, a var can contain a string or number or another var-array). Normally that is all needed to pass even complex data into a view or template. You HTML then only needs to echo some array members and or foreach over subarrays. This is a very simple technique to create a template. You can use PHP for it, so you're actually really flexible (just draw the border which code belongs into your view layer and which is part of the application, e.g. providing values for the view).
Move SQL out of your code. Move the database interaction code away. Create yourself one or multiple objects that have methods which return the data in a way you need (consume) it in your actual processing code, like $component->getThatData() which then returns data in a normalized form. Make those components then use a dedicated database component to talk over with the database. In your application code (business logic) only use the database component and preferably the objects you create to get the data, so you don't have any line of SQL any longer inside your main code.
Divide and Conquer your application code: Divide your code into Transaction Scripts. They are often easy to create from existing spaghetti code and will be probably become the said Separator you're looking for in middle terms. They will then have the role to process data and passing it on (into the output/view).
Use clear language: If you have complex formatted string data that is not normalized, write yourself Parser classes that do the work for you and which can be easily re-used (if that's the case in your application). As you should look forward to minimize the use of plain SQL in your code, you should also look forward to move complex regular expressions away as well. Encapsulate what varies is a key point. Same applies to long routines to just handle some data (e.g. sort, order and arange it in another format), move them into components of each own and think about how you can make them accessible and re-useable.
Make your code functioning: Find out about the logic how you invoke functionality in your program. You can try to separate functionality away from how it's invoked. E.g. some routine that invokes any of the Transaction Scripts. This might not be necessary if you request PHP files directly via the browser, as those are then your transaction scripts and the webserver takes care to resolve the command send via URL into your application to the transaction script. But you should then wrap any logic needed to process the incoming command and it's parameters into re-useable components (e.g. a Request class that contains standard code to get the URL and or variables from a HTTP request).
Create a common entry-point by including the same file at the very top of all files that are called via the browser. You can then put common code (like setting up the application session state object and initializing the database component) into it, see as well Application Controller
Remove duplication by looking for literally duplicated code. Wrap it into a function or class. Create a library folder for your own application into which you put your includes. If you follow a common pattern with Classnames and Namespacing, you can easily use an autoloader to keep inclusion easy. Make your library apart from third-party code. Place all third-party code into a library folder of it's own with one subdirectory for each third-party component.
Use lightweight, existing components. Lightweight is important because you have your own code already, you don't want to turn and press it all at once onto a framework. Existing is important because you don't want to re-invent the wheel. You will have enough work for your own refactoring your code. After you feel better about your application and you still have power and will, you can always write everything new. But if you're alone or in a small team, Existing is pretty powerful. Simple libraries are for example:
Create Application State, e.g. as an object you can make use of in case some components need to know about the application state or each other without direct interaction. By default in PHP if you don't have one, global and global static variables are used to create state. However these variables can make your live hard as code grows. When you create an application state object, it's clear which components make use of it, access to it can be controlled (e.g. calling a method instead of reading a variable, which can help with debugging) and components as well can find out if it's the right time in the application flow to come into action. It's also a good tool for refactoring your code over time.
Preserve a Working Application, keep your code in a state to run. Ideally this would be backed up by automatic tests. Consider that you need to rewrite much. For example if you start to integrate a database component, do it. Move all your existing code to it in one step. So who tells you it still runs? Use git for better undo and to test stuff. That's more important than choosing the right library. Preserving a working application is also always the key point because that's why you change it, right?
Why not use a templating engine? TWIG is very easy to use and great for this sort of thing. It is often used with the Symfony framework, but can easily be used on its own.
function render() {
//start output buffering (so we can return the content)
ob_start();
//bring all variables into "local" variables using "variable variable names"
foreach($this->vars as $k => $v) {
$k = $v;
}
//include view
include($this->file);
$str = ob_get_contents();//get teh entire view.
ob_end_clean();//stop output buffering
return $str;
}
在控制器中,您可以包含模型文件,调用数据的特定类和函数。例如,使用渲染函数调用视图文件,
$view = new view('../view/data.php');
$view->name = 'Your Name';
$view->bio = "I'm a geek.";
echo $view->render();
您可以根据您的要求返回或回显您的视图
as you don't need user input and store session. You can just create a controller -> model & controller -> view structure
the controller: will help you get data from DB (via. model) and embed data into view.
You can create 3 folders controller, model, and view. In each folder, you can create files based on your needs(e.g.MVC for User).
The model can access static objects written in mysqli.inc.php or pdo.inc.php based on your need you can write a template for connection, query, disconnection, in all your model classes.
In model file, you can call static function DB::query('SELECT/INSERT/UPDATE/DELETE', );
For view, you will need a render function to embed data into HTML Code for example
function render() {
//start output buffering (so we can return the content)
ob_start();
//bring all variables into "local" variables using "variable variable names"
foreach($this->vars as $k => $v) {
$k = $v;
}
//include view
include($this->file);
$str = ob_get_contents();//get teh entire view.
ob_end_clean();//stop output buffering
return $str;
}
In the controller, you can include your model file call particular class and function for data. Call view file with render function for example,
$view = new view('../view/data.php');
$view->name = 'Your Name';
$view->bio = "I'm a geek.";
echo $view->render();
you can either return or echo your view based on your requirement
发布评论
评论(3)
恭喜您了解如何改进代码。这是前提,你需要想要改进它,而且这个话题很长。所以你的意志至关重要。
我开始时会比较轻松,然后尝试给出一些提示。当您缺少经验时,请寻找一个起点,最肯定的是下面列表中的最后一个。但首先要做的事情是:
要将某些内容彼此分开,您需要有一些分隔的代码:
这里的分隔符实际上也是PHP代码,但我想您已经明白了。
正如您所看到的,只有 Separator 与 HTML/CSS 和 PHP/SQL 进行对话。
因此,HTML/CSS 和 PHP/SQL 都需要有一个带有 Separator(之间的线)的接口才能完成此操作。
通常在程序中,您传递已处理的数据。数据非常动态,并且可能具有复合复杂性,尤其是当您将数据传递到应正确格式化数据的输出例程时。
有多种方法可以编写这样的分隔符(或多个)。您可以分层您的软件或提供在其区域或域中执行操作的组件。例如,您有一个数据库层或数据库组件来负责与数据库的交互。
或者您有一个模板引擎,负责将字符串和数组放入一些可读的 HTML 中。
简而言之,这就是软件设计的面食理论:
就像我们在生活中吃不同的面食一样,在编程时我们也需要处理所有这些不同类型的代码,并且随着时间的推移我们会形成自己喜欢的口味。当我们还是个孩子的时候,我们会吃饭,但随着时间的推移,我们开始自己做饭并改变食谱。
所以我认为这是一个很好的观点,你只是不想在接下来的几周内吃MVC Framework X,只是因为有人告诉你这是现在的吃法。吃东西之前,还有品尝,对吗?更不用说快餐了,你知道像这些带酱的面条——只加水。呃。
我不知道你的输出需要哪些数据以及输入是什么。以下是针对输出 HTML/CSS 并与 MySQL 数据库交互的应用程序的一些粗略重构技巧。这不可能是一个完整的列表,描述只能粗略地概述一些想法:
style
属性(如果还有)。这使得您的 CSS 代码可重用并且更加模块化。它将帮助您找到 HTML 内部的缺陷,并将结构 (HTML) 与表示 (CSS) 分开。有效的 HTML 从有效使用 CSS 开始,这两者一起非常强大,通常这已经可以减轻您的程序输出例程。考虑一下您的应用程序中是否需要已经有复杂的输出,或者您是否可以只传递带有子元素的数组(键是 var,var 可以包含字符串或数字或另一个 var 数组)。通常,将复杂的数据传递到视图或模板中都需要这些。然后,您的 HTML 只需要在子数组上回显一些数组成员和/或
foreach
。这是创建模板的非常简单的技术。您可以使用 PHP,因此实际上非常灵活(只需绘制属于您的视图层的代码以及属于应用程序的一部分的边框,例如为视图提供值)。$component->getThatData()
,然后它以标准化形式。创建这些组件,然后使用专用的数据库组件与数据库进行通信。在您的应用程序代码(业务逻辑)中,仅使用数据库组件,最好是您创建的对象来获取数据,因此您的主代码中不再有任何 SQL 行。现有很重要,因为你不想重新发明轮子。您将有足够的工作来重构您的代码。当你对你的申请感觉更好并且你仍然有力量和意志之后,你总是可以写出新的东西。但如果您独自一人或在一个小团队中,Existing 就非常强大。
简单的库例如:
Congrats for looking how you can improve code. That's the precondition, you need to want to improve it and the topic is lengthy. So your will is crucial.
I start lightly and then try to give some tips. As you're missing experience, look for one point to start with, most certainly the last one of the list below. But first things first:
To separate something from each other, you need to have some code that separates:
The Separator here actually is PHP code as well, but I think you get the idea.
As you can see only the Separator talks with HTML/CSS and PHP/SQL.
So both HTML/CSS and PHP/SQL need to have an interface with Separator (the line between) to make this work.
Normally in a program you pass around data that get's processed. The data is pretty dynamic and can have a compound complexity, especially if you pass data to an output routine that should format it properly.
There are multiple ways of how such a Separator (or multiple of them) can be written. You can layer your software or provide components that do things in their area or domain. E.g. you have a database layer or database component that takes care about the interaction with the database.
Or you have a templating engine that takes care to put your strings and arrays into some readable HTML.
In short this is the pasta theory of software design:
Like we eat different pasta in our lives, when programming we need to deal with all these different type of code as well, and we develop our own preferred taste over time. As a kid we're feed but over time we start to cook something our own and vary the recipes.
So I think it's a good point you just don't want to now eat MVC Framework X with much awesome for the next weeks only because somebody told you it's the way to eat now. And before eating, there is tasting, right? Not to mention fast-food, you know like these noodles with sauce in package - only add water. Urgh.
I don't know which data your output needs and what the input is. Following are some rough refactoring tips for applications that output HTML/CSS and interact with a MySQL database. This can not be a complete list and the descriptions can only roughly outline some thoughts:
style
attributes if you still have some. This makes your CSS code re-useable and more modular. It will help you to find flaws inside your HTML and to separate the Structure (HTML) from the Presentation (CSS). Effective HTML start with effective usage of CSS, those two are very powerful together and often this already will lighten your programs output routines.Consider if you need to already have complex output inside your application or if you can just pass on arrays with subelements (a key is a var, a var can contain a string or number or another var-array). Normally that is all needed to pass even complex data into a view or template. You HTML then only needs to echo some array members and or
foreach
over subarrays. This is a very simple technique to create a template. You can use PHP for it, so you're actually really flexible (just draw the border which code belongs into your view layer and which is part of the application, e.g. providing values for the view).$component->getThatData()
which then returns data in a normalized form. Make those components then use a dedicated database component to talk over with the database. In your application code (business logic) only use the database component and preferably the objects you create to get the data, so you don't have any line of SQL any longer inside your main code.Existing is important because you don't want to re-invent the wheel. You will have enough work for your own refactoring your code. After you feel better about your application and you still have power and will, you can always write everything new. But if you're alone or in a small team, Existing is pretty powerful.
Simple libraries are for example:
为什么不使用模板引擎呢? TWIG 非常易于使用,非常适合此类事情。它通常与 Symfony 框架一起使用,但也可以轻松地单独使用。
Why not use a templating engine? TWIG is very easy to use and great for this sort of thing. It is often used with the Symfony framework, but can easily be used on its own.
因为您不需要用户输入和存储会话。
你可以只创建一个控制器->模型与控制器->视图结构
控制器:将帮助您从数据库获取数据(通过模型)并将数据嵌入到视图中。
您可以创建 3 个文件夹:controller、model 和 view。在每个文件夹中,您可以根据需要创建文件(例如MVC for User)。
该模型可以根据您的需要访问 mysqli.inc.php 或 pdo.inc.php 中编写的静态对象,您可以在所有模型类中编写用于连接、查询、断开连接的模板。
在模型文件中,您可以调用静态函数 DB::query('SELECT/INSERT/UPDATE/DELETE', );
对于视图,您需要一个渲染函数来将数据嵌入到 HTML 代码中,例如
在控制器中,您可以包含模型文件,调用数据的特定类和函数。例如,使用渲染函数调用视图文件,
您可以根据您的要求返回或回显您的视图
as you don't need user input and store session.
You can just create a controller -> model & controller -> view structure
the controller: will help you get data from DB (via. model) and embed data into view.
You can create 3 folders controller, model, and view. In each folder, you can create files based on your needs(e.g.MVC for User).
The model can access static objects written in mysqli.inc.php or pdo.inc.php based on your need you can write a template for connection, query, disconnection, in all your model classes.
In model file, you can call static function DB::query('SELECT/INSERT/UPDATE/DELETE', );
For view, you will need a render function to embed data into HTML Code for example
In the controller, you can include your model file call particular class and function for data. Call view file with render function for example,
you can either return or echo your view based on your requirement