search
HomeBackend DevelopmentPHP TutorialFunctions you must know when entering Phalcon 'Phalcon Entry Guide Series 2'

Let us learn Phalcon through examples

  • Contents of this series
  • Preface
  • 1. Project structure
  • 2. Entry file
  • 3. Configuring Nginx
  • 4. Controller jump
  • 5. Database addition, deletion, modification and query
    • Insert data
    • Modify data
    • Delete data
  • 6. Code optimization
  • Summary

Directory of this series

1. Installing Phalcon on Windows "Phalcon Pit Guide Series 1"

Preface

The previous article introduced you to the installation of Phalcon and the use of Phalcon development tools Created projects, controllers, and models. Just did a few simple operations.

In this issue, we will continue to talk about the actual use of Phalcon.

1. Project structure

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

From As can be seen from the above figure, this directory structure is very similar to the TP framework. The corresponding directories will not be explained one by one. Let me tell you about the migrations directory.

This directory is just like the database migration in laravel. I won’t go into details on how to use it!

The framework structure is not fixed. Like ThinkPHP, you can register a namespace to modify the directory structure.

In the Phalcon framework, Kaka’s recent project was also developed using multiple modules. However, the directory structure is also different from the directory generated using the Phalcon development tool.

Everything remains the same, they all look the same.

2. Entry file

An essential file for each framework, index.php seems to be all Developer default.

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

Then it is also essential in the framework of Phalcon.

I won’t analyze the source code in detail about what is loaded here. It is not necessary. If you want to see the source code analysis, you can search for ThinkPHP framework source code analysis.

The general execution is to perform dependency injection first, and use /config/services.php to introduce some files. What you need to pay attention to is that the database connection is made here.

This file/config/router.phpYou will know what it is by looking at the name, routing! How to set up routing will be discussed later.

Get the configuration information after passing the first step of dependency injection.

The last line of code is include APP_PATH . '/config/loader.php';Register the directory obtained from the configuration information.

3. Configure Nginx

In the first issue of the article, the project was not configured. Let’s do a simple configuration next.

Phalcon provides three ways of configuration, let’s just use the simplest one first.

server {
        listen        80;
        server_name  www.kakaweb.com;
        root   "D:/phpstudy_pro/WWW/phalcon/public";
        index index.php index.html error/index.html;
	    location / {
	        try_files $uri $uri/ /index.php?_url=$uri&$args;
	    }

        
        location ~ \.php(.*)$ {
            fastcgi_pass   127.0.0.1:9002;
            fastcgi_index  index.php;
            fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_param  PATH_INFO  $fastcgi_path_info;
            fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;
            include        fastcgi_params;
        }
	
	    location ~ /\.ht {
	        deny all;
	    }}

The above is the configuration of Kaka. If you are also using PhpStudy, you can directly copy it and use it.

4. Controller jump

In the first article, the control was created using the phalcon development tool If you haven't created a project yet, you need to read the first article!

Let’s see how the visit goes first.

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

Code

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

You can see that in the index controller, another method kaka is also established.

Mainstream frameworks are configured with the index controller as the default access path. How to access this kaka is the same as other frameworks.

The access link is http://www.kakaweb.com/index/kaka.

is the domain name controller method name. It should be noted that the method name here does not need to include Action.

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

Practice the official case.

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

You can see that the output result is a link

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

This link will jump directly to the Signup controller. Next, use the developer tools to generate this controller.

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

Then click the button just now and it will jump to the Signup controller.

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

Let’s talk about the controller first.

5. Database addition, deletion, modification and query

You can see that it is defined in advance in the model file Okay, two methods, no matter what they are, let’s try them first.

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

Write the following code directly in the controller

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

##Query results

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

It can be seen that

    find method is to get all the data
  • findFirst only takes the first piece of data
  • find(15) Query the data with id 15
  • find("type = 'mechanical'"); Conditional search

Insert data

实现代码

    public function holdAction ()
    {
        $user = new User();

        $phql = "INSERT INTO User (name, age, sex) VALUES (:name:, :age:, :sex:)";

        $status = $user->modelsManager->executeQuery($phql, array(
            'name' => "咔咔1",
            'age' => 24,
            'sex' => 1
        ));

    }

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

这里需要注意一下这个SQL语句$phql = "INSERT INTO User (name, age, sex) VALUES (:name:, :age:, :sex:)";

在这里User指的是模型,并不是数据库表名。

修改数据

实现代码

    public function modifyAction ()
    {
        $user = new User();

        $phql = "UPDATE User SET name = :name:, age = :age:, sex = :sex: WHERE id = :id:";

        $status = $user->modelsManager->executeQuery($phql, array(
            'id' => 20,
            'name' => "咔咔2",
            'age' => 25,
            'sex' => 2
        ));
    }

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

    public function deleteAction ()
    {
        $user = new User();

        $phql = "DELETE FROM User WHERE id = :id:";

        $status = $user->modelsManager->executeQuery($phql, array(
            'id' => 20
        ));

    }

可以看到已经没有结果了

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

这时你会发现,在检索数据的时候用的框架自带的方法,到增、删、改使用的类似于原生了。

对于这个问题,如果你是新手建议会那种方式就用那种方式,因为工期可不等你。

Kaka will also talk to you about the method of using framework modifications. Don’t worry about this. The next article will be published!

6. Code Optimization

In Section 5, did you find this problem?

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

In all methods, the User model is instantiated, and this is OK.

But think about it, if you use this method for a full project in the early stages of the project, and find that you need to change the name in the middle, what would you do?

Search the User keyword globally and change it to the modified name?

To be honest, few programmers dare to do this kind of operation because you don’t know where the problem will occur.

So Kaka will tell you a method for unified management of these models.

Functions you must know when entering Phalcon Phalcon Entry Guide Series 2

You can declare the model in your own way.

Then initialize in the controller and instantiate the model here.

At this point you are thinking that if the table name is changed, do we only need to modify the name in the initialization method?

Summarize

This article introduces you to the necessary functions when using a framework.

Although a native-like method is used in the process of adding, deleting, modifying, and checking, this method is rarely used in any framework.

But no matter which way it is, it’s all code, right? Don't sneer at it, the framework functions can change at will, but these SQL statements will never change.

#Persistence in learning, persistence in writing, and persistence in sharing are the beliefs that Kaka has always adhered to since his career. I hope that Kaka’s articles on the huge Internet can bring you a little bit of help. I’m Kaka, see you next time.

The above is the detailed content of Functions you must know when entering Phalcon 'Phalcon Entry Guide Series 2'. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor