Core PHP and PHP frameworks: comparative analysis of two approaches for backend development

The advantages and disadvantages of PHP web development using Core PHP and PHP frameworks. Security and performance are investigated. The recommendations on using both approaches. The structure of application and key development things are highlighted.

Рубрика Программирование, компьютеры и кибернетика
Вид статья
Язык английский
Дата добавления 10.10.2023
Размер файла 381,7 K

Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже

Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.

Размещено на http://www.allbest.ru/

Core PHP and PHP frameworks: comparative analysis of two approaches for backend development

Marian Slabinoha, PhD in Engineering, Associate Professor at Computer Systems and Networks Department, Ivano-Frankivsk National Technical University of Oil and Gas

The purpose of this paper is to compare two approaches of backend development using the PHP programming language - Core PHP and PHP frameworks. Both approaches are popular, but, as in every other language, using frameworks saves developer time and allows him not to implement routine connected with the trivial operations.

Still, when we are talking about performance and “weight” of the web-application, we can say that using frameworks often includes a lot of redundant and unnecessary code from packages that are used, and a lot of web-developers don't control that. As a result, the developed web-applications become heavier and consume more resources of server systems. Moreover, frameworks approach is often used for very simple applications that can be easily implemented using Core PHP and based on a few files of code. This creates unnecessarily large projects solving the small and simple tasks.

The aim of this paper is to highlight the advantages and disadvantages of PHP web development using Core PHP and PHP frameworks. The security and performance are investigated mostly, but some smaller things are taken into account as well. The recommendations on using both approaches are given to provide most effective combination of development experience and performance.

As the result of comparison analysis, the framework-like MVC application architecture is proposed to build tiny lightweight web applications for custom tasks (in our case, the vocabulary website). The structure of the application is provided and key development things are highlighted (using Core PHP).

The perspectives of modification for solving trivial problems like RESTful backend app or bearer token authentication are discussed.

Key words: sustainable web development, performance optimization, PHP frameworks, MVC architecture, Core PHP.

Core PHP та PHP фреймворки: порівняльний аналіз двох підходів до розробки серверних додатків

Мар'ян Слабінога, кандидат технічних наук, доцент, доцент кафедри комп'ютерних систем і мереж, Івано-Франківський національний технічний університет нафти і газу

Метою даної роботи є порівняння двох підходів розробки серверних додатків з використанням мови програмування PHP - Core PHP («чистого PHP») і PHP фреймворків. Обидва підходи популярні, але, як і в будь-якій іншій мові, використання фреймворків економить час розробника і дозволяє йому не реалізовувати рутину, пов'язану з тривіальними операціями.

Однак, коли ми говоримо про продуктивність і розміри веб-додатка, можна сказати, що використання фреймворків часто включає багато зайвого та непотрібного коду з пакетів, які використовуються. Часто, веб-розробники не приділяють достатньо уваги контролю за цими процесами, в результаті чого розроблені web-додатки стають важчими і споживають більше ресурсів серверних систем. Більше того, підхід з використанням фреймворків часто використовується для дуже простих додатків, які можна легко реалізувати за допомогою Core PHP і на основі кількох файлів коду. Це створює невиправдано великі проекти, що вирішують дрібні та прості завдання.

Мета цієї статті - висвітлити переваги та недоліки веб-розробки PHP з використанням Core PHP та PHP фреймворків. Здебільшого досліджуються безпека та продуктивність, але враховуються й деякі менш критичні речі. Надано рекомендації щодо використання обох підходів, щоб забезпечити найбільш ефективне поєднання досвіду розробки та продуктивності.

В результаті порівняльного аналізу пропонується MVC архітектура додатка, подібна до фреймворку, для створення невеликих легких веб-додатків для користувацьких завдань (у нашому випадку, веб-сайт словник). Надається структура програми та виділено ключові моменти розробки (за допомогою Core PHP).

Обговорюються перспективи модифікації для вирішення тривіальних проблем, таких як серверний додаток RESTful або аутентифікація з допомогою Bearer-токенів.

Ключові слова: веб-розробка в контексті сталого розвитку, оптимізація продуктивності, PHP-фреймворки, архітектура MVC, «чистий» PHP.

PHP has been one of the most popular backend developments for a long time. LAMP stack as the platform configuration remains the most popular way to host the web-sites. According to W3Techs [1], 77.4 % of websites whose server-side programming language is known, use PHP.

PHP started as the scripting language, but soon became the powerful tool for the “classic” programming approach. As a result, a lot of different frameworks that used PHP as a basic programming language were developed and released. Of course, this made developers work easier and less time consuming, providing all-in-one popular functionality of the application.

However, the performance of the PHP frameworks remains questionable, compared to Core PHP. Moreover, a lot of small backend web applications are written using PHP frameworks and include a lot of redundant code from different packages, so most functions from these packages remain unused.

The aim of this paper is to compare two approaches and give the recommendations regarding usage of each approach depending on the project characteristics.

So, when we are talking about the difference between using Core PHP and PHP frameworks, a couple of things should be considered. First of all (and this is the main purpose of the frameworks) is the convenience of the development process. PHP frameworks are known to be time-saving while developing large applications [2]. The reason of this frameworks approach advantage is including the packages that solve standard web development routine in your project without having to write it from scratch. This includes the authorization process, routing and using the database as an abstraction. Developers can simply use the pre-developed functions without writing them by themselves.

Second big advantage of the framework is team interaction during the development process. Core PHP requires the developer team to agree on a lot of small and big things - how to break the app structure into files, packages or object-oriented programming entities, etc. In the case of a framework you already have the skeleton of your project and stick to the design recommendations of that framework.

Easy maintenance and scalability is the next advantage of PHP frameworks [3]. The requests, loading balance and many other things connected with the app performance are already developed and configured when using frameworks. This allows you to build relatively big and complex applications without worrying about how it will behave when the number of customers increases.

When talking about advantages of using Core PHP, the first one that comes to mind is controlling all your code. When developer builds the application from scratch and does it in the proper way, using KISS (Keep It Simple Stupid) and DRY (Don't Repeat Yourself) principles, he gets the application that is fully transparent and traceable. This allows the developer to rely on himself at major part of the code and not to worry about packages updates, version conflicts, etc.

But the key advantage of the Core PHP is performance. Author of the paper [4] gives the detailed analysis of CRUD (Create - Read - Update - Delete) operations performance for Core PHP and popular frameworks - Phalcon, CodeIgniter, Laravel and Symphony. According to the research, the fastest framework (Phalcon) application executed CRUD operations more than 2 times slower than Core PHP application, while the most popular PHP framework, Laravel, was up to 400 times slower than Core PHP.

Worth to note that usage of Core PHP is not just about the performance, but also improves the resource usage. In example, according to [2], create action consumes 0.14 Megabytes of memory in Core PHP, 0.17 Megabytes when using Phalcon and 9.42 Megabytes when using Laravel. This is directly connected with the number of called functions during this operation, which is equal to 50 in Core PHP 225 for Phalcon and 1253 for Laravel. The difference between these numbers is significant.

Thus, in the projects that don't require much scalability and are not very complicated we need to omit the usage of the frameworks. Based on the information provided by HTTP Archive [5], the average web page size in 2010 was 702 KB compared to in 2016 which is 2232 KB. With the increase in size of every web component and the addition of video, web page size has increased by 1,530 KB or 317 % from 2010 to 2016. Developers should keep in mind that every request their application consumers do to the server is the electricity consumption as well as working resource of the server devices.

The last but not least point in discussing the Core PHP and PHP Frameworks is the security. This point is where we can summarize the comparison, because the same thing applies to all aspects of web application web development. Everything that is done in terms of security in frameworks, obviously can be implemented in Core PHP. When using the Core PHP, you'll get clear traceable code that uses minimal amount of resources and executes faster, but the whole development process will be significantly more time consuming and complicated than the development process that uses frameworks. Also, the bigger the Core PHP project, the harder it will be to support and develop, especially when working in a team.

So, the conclusions of the comparative analysis are:

1) if a project is large in terms of scope, is expected to be scaled in future and is developed by a team, it's better to use PHP frameworks;

2) if the project is relatively small and simple, amount of customers is known and it is supported by small group of developers or single developer, it's better to use Core PHP to keep the project simple and avoid unnecessary resource consumption.

The main question that remains after these conclusions is how do we keep the advantages of MVC architecture when not using MVC framework. Let's consider the simple example - dictionary application to store and search through translations of words and word combinations between English and Ukrainian languages. The database structure contains the following tables:

- categories (to store translation categories);

- en_lang_parts (to store the names of English language parts);

- invitations (to store the invitations that administrator sends to the potential editors);

- remarks (to store the editions made by editors into existing translations);

- roles (to store user roles);

- translations (to store the translations and it's context);

- ua_lang_parts (to store the names of Ukrainian language parts);

- users (to store the user data.

The sitemap of the project is given on Fig. 1.

Figure 1 - Project sitemap

The functionality of the project is achieved through the structure shown on Fig. 2.

Figure 2 - Project structure

Root project folder contains two folders (app and assets) and three files:

- config.php file is used to store environment variables like database credentials, project root folder path, project URL etc;

- .htaccess file contains the configuration for Apache. The main purpose of this file in this project is to map all requests to index.php, no matter what the sub-URL is;

- index.php file reads the config.php file and calls the router, which is located in app folder.

Assets folder contains three folders:

- css - for all CSS files of the project;

- js - for all the scripts;

- img - for all the images in the project.

App folder contains two files and three folders:

- router.php file checks the current url the user is located at and loads proper controller to show the page;

- dbconnect.php creates the mysql connection using the credentials so it can be used by models later;

- models folder contains the models for each project entity that are represented with a file that contains the number of functions providing CRUD implementation and additional functionality (like checking the email for availability during registration;

- controllers folder contains the controller files (one for each project page) that call the proper models to provide the data and includes views to create server-side rendering of the result page;

- views folder contains html code fragments for common parts (like header and footer) and specific pages).

This structure is an example of how a simple application can be implemented with Core PHP in an MVC way. Because the whole application is server-side rendered, we can manage access using the PHP sessions. However, if we need to make the app universal for any web clients, it's better to provide an API and use RESTful architecture. For this, we only need to modify the app excluding views and replacing them by generating proper JSON-formatted responses in controllers and control the API calls through the $_ SERVER["REQUEST_METHOD"] variable (to retrieve the post type). To authenticate the web client, Bearer token can be used and retrieved through processing of the $_SERVER[`HTTP_ AUTHORIZATION'] variable.

In conclusion, it is worth to note that cleanness and performance of each application is mostly dependent on developer skills and his ability to simplify the developed apps. Avoiding unnecessary complexity is the key step to build a sustainable web environment, and this is the task of every developer.

Acknowledgements. Author wants to thank the Armed Forces of Ukraine and all the defenders of Ukraine that give us the possibility to proceed scientific and engineering work in time of war.

References

1. Usage statistics of PHP for websites. (2022). W3Techs.

2. Pirog, W. (2018). How a PHP framework can speed up the development process. Polcode. Retrieved May 25, 2022,

3. eTatvaSoft. (2016). Basic difference in Web Development with Core PHP and PHP Frameworks. eTatvaSoft.

4. Samra J. (2015). Comparing Performance of Plain PHP and Four of Its Popular Frameworks (Dissertation).

5. KeyCDN. (2018). The Growth of Web Page Size.

framework application security

Література

1. Онлайн ресурс Web Dev

2. Онлайн ресурс Polcode. How a PHP framework can speed up the development process: веб-сайт.

3. Онлайн ресурс eTatvaSoft - Basic difference in Web Development with Core PHP and PHP Frameworks

4. Samra J. Comparing Performance of Plain PHP and Four of Its Popular Frameworks: Dissertation on Computer Sciences. Linnaeus University, Kalmar, 2015. 33 p.

5. Онлайн ресурс KeyCDN - The Growth of Web Page Size

Размещено на Allbest.ru

...

Подобные документы

  • IS management standards development. The national peculiarities of the IS management standards. The most integrated existent IS management solution. General description of the ISS model. Application of semi-Markov processes in ISS state description.

    дипломная работа [2,2 M], добавлен 28.10.2011

  • Кодовые названия процессоров Core 2: Conroe, Merom, Kentsfield и Penryn. Архитектура Core Micro Architecture. Краткое сравнение микроархитектур Intel Core и AMD K8. Аналитический обзор процессоров на базе ядра Conroe: тактовая частота и ценовой диапазон.

    реферат [1,4 M], добавлен 15.11.2014

  • Overview history of company and structure of organization. Characterization of complex tasks and necessity of automation. Database specifications and system security. The calculation of economic efficiency of the project. Safety measures during work.

    дипломная работа [1009,6 K], добавлен 09.03.2015

  • Процессоры Intel Core 2 Duo, энергопотребление. Размер кристалла Core 2 Duo и число транзисторов. Технологии управления энергопотреблением Core 2 Duo. Ultra Fine Grained Power Control. Индикация энергопотребления процессора/PSI-2. Цифровые термодатчики.

    курсовая работа [5,4 M], добавлен 16.01.2009

  • Lists used by Algorithm No 2. Some examples of the performance of Algorithm No 2. Invention of the program of reading, development of efficient algorithm of the program. Application of the programs to any English texts. The actual users of the algorithm.

    курсовая работа [19,3 K], добавлен 13.01.2010

  • История создания и развития компьютерных процессоров Intel. Изучение архитектурного строения процессоров Intel Core, их ядра и кэш-память. Характеристика энергопотребления, производительности и систем управления питанием процессоров модельного рядя Core.

    контрольная работа [7,6 M], добавлен 17.05.2013

  • Архитектура операционной системы Android. Инструменты Android-разработчика. Установка Java Development Kit, Eclipse IDE, Android SDK. Настройка Android Development Tools. Разработка программы для работы с документами и для осуществления оперативной связи.

    курсовая работа [2,0 M], добавлен 19.10.2014

  • Основные алгоритмические структуры. Запись алгоритма в словесной форме, в виде блок-схемы. Система команд исполнителя. Язык высокого уровня. Создание программы и её отладка. Интегрированные среды разработки: Integrated Development Environment, IDE.

    лекция [61,7 K], добавлен 09.10.2013

  • Сrime of ciber is an activity done using computers and internet. History of cyber crime. Categories and types of cyber crime. Advantages of cyber security. The characteristic of safety tips to cyber crime. Application of cyber security in personal compute

    презентация [203,5 K], добавлен 08.12.2014

  • Складові частини мікропроцесорної системи на базі Intel Core i7. Ноутбук HP Pavilion dv7 на базі мобільної платформи Intel Core i7. Суть технології Hyper-Threading. Вибір, класифікація, модернізація и ремонт ноутбуків. Самоперевірки при включенні POST.

    курсовая работа [6,6 M], добавлен 18.06.2011

  • Practical acquaintance with the capabilities and configuration of firewalls, their basic principles and types. Block specific IP-address. Files and Folders Integrity Protection firewalls. Development of information security of corporate policy system.

    лабораторная работа [3,2 M], добавлен 09.04.2016

  • Описание конфигурации компьютера, предназначенного для игр. Ознакомление с характеристиками процессора Intel core 2 Quad. Тестирование уменьшения объема кэш-памяти второго уровня. Анализ видеокарты ASUS Radeon HD 7850 DirectCU II, материнской платы.

    курсовая работа [3,6 M], добавлен 04.01.2016

  • Технология конструирования программного обеспечения, надежно и эффективно работающего в реальных компьютерах. Модель быстрой разработки приложений (Rapid Application Development) как один из примеров применения инкрементной стратегии конструирования.

    реферат [666,5 K], добавлен 24.06.2009

  • Модули, входящие в пакет программного обеспечения. Project Menagement, Methodology Management, Portfolio Analysis, Timesheets, myPrimavera, Software Development Kit, ProjectLink. Иерархическая структура Primavera и ее взаимосвязь с программой MS Project.

    контрольная работа [9,5 K], добавлен 18.11.2009

  • Програмний засіб моніторингу реалізації проектів з побудовою графіків та завданням відхилень. Вибір моделі життєвого циклу розробки додатків Rapid Application Development об'єктно-орієнтованою мовою програмування C# на платформі Microsoft .NET Framework.

    дипломная работа [1,4 M], добавлен 11.09.2012

  • Technical methods of supporting. Analysis of airplane accidents. Growth in air traffic. Drop in aircraft accident rates. Causes of accidents. Dispatcher action scripts for emergency situations. Practical implementation of the interface training program.

    курсовая работа [334,7 K], добавлен 19.04.2016

  • Information security problems of modern computer companies networks. The levels of network security of the company. Methods of protection organization's computer network from unauthorized access from the Internet. Information Security in the Internet.

    реферат [20,9 K], добавлен 19.12.2013

  • Розробка структури, алгоритму роботи програми, яка забезпечує можливість покупки товарів. Створення списку користувачів та списку продуктів. Розробка структур даних та основних процедур програми. Алгоритм створення платформи під назвою "Сlaude Monet".

    курсовая работа [121,3 K], добавлен 14.05.2019

  • Technical and economic characteristics of medical institutions. Development of an automation project. Justification of the methods of calculating cost-effectiveness. General information about health and organization safety. Providing electrical safety.

    дипломная работа [3,7 M], добавлен 14.05.2014

  • Создание электрической схемы проектируемого устройства с помощью графического интерфейса. Улучшение кодовой базы с помощью рефакторинга. Разработка алгоритма работы программы. Использование методики Test driven development, написание тестового покрытия.

    курсовая работа [1,3 M], добавлен 15.02.2016

Работы в архивах красиво оформлены согласно требованиям ВУЗов и содержат рисунки, диаграммы, формулы и т.д.
PPT, PPTX и PDF-файлы представлены только в архивах.
Рекомендуем скачать работу.