Быстрое создание crud-интерфейса на php с помощью продвинутого инструмента генерации crud c использованием pdo

Create DAO Layer Into Spring Boot Appplication

Let’s create dao layer for spring employee model. We will create file into folder and added below code into this file –

package com.example.restapiexample.models;

import java.util.List;

import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional;

import org.springframework.stereotype.Repository;

import com.example.restapiexample.models.Employee;

@Repository @Transactional public class EmployeeDao { @PersistenceContext private EntityManager entityManager; /** * Return all the employee stored in the database. */ @SuppressWarnings(«unchecked») public List<Employee> getAll() { return entityManager.createQuery(«from Employee»).getResultList(); } public Employee getById(int id) { return entityManager.find(Employee.class, id); } /** * Save the employee in the database. */ public Employee create(Employee emp) { entityManager.persist(emp); int id = emp.getId(); return entityManager.find(Employee.class, id); } /** * delete the employee in the database. */ public Boolean delete(Employee emp) { if (entityManager.contains(emp)) entityManager.remove(emp); else entityManager.remove(entityManager.merge(emp)); return true; } }

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49


import java.util.List;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

import javax.transaction.Transactional;

import org.springframework.stereotype.Repository;

import com.example.restapiexample.models.Employee;





privateEntityManager entityManager;


   * Return all the employee stored in the database.    */



returnentityManager.createQuery(«from Employee»).getResultList();


publicEmployee getById(intid){




   * Save the employee in the database.    */

publicEmployee create(Employee emp){






   * delete the employee in the database.    */

publicBooleandelete(Employee emp){









In this tip, we have discussed what CRUD is in SQL Server, and why CRUD is important and how we can extend this CRUD concept from DML to DDL.

For a new DBA to grasp the knowledge of SQL Server, it may be good to look at SQL Server operations from a CRUD perspective, and this may make learning much easier as we can categorize the learning under each C/R/U/D.

Next Steps

The CRUD concept is the foundation of operations in any RDBMS system, and you can read more CRUD-related topics on MSSQLTips.com as listed below:

  • Standardizing SQL Server CRUD Templates with Rollback Plans

  • Comparing performance for the MERGE statement to SELECT, INSERT, UPDATE or DELETE

  • Using MERGE in SQL Server to insert, update and delete at the same time

About the author

Jeffrey Yao is a senior SQL Server consultant, striving to automate DBA work as much as possible to have more time for family, life and more automation. View all my tips

Related Resources

Become a paid author

🔗 Let’s talk about CRUD

CRUD is an acronym that comes from the world of databases. Each letter stands for one type of action that a user can perform on a set of data: Create, Read, Update, and Delete. In relational databases, the four activities match the SQL commands INSERT, SELECT, UPDATE and DELETE.

It’s possible to apply the CRUD concept to the world wide web and its underlying HTTP protocol. Every URL points to a resource, that is, a set of data. And you can access those with different HTTP verbs: GET, PUT, POST and DELETE. Spoiler alert: these verbs do not match CRUD exactly. But more about that later.

Many APIs follow this paradigm, so you’d be in good company. For developers who have already worked with other APIs, the developer experience will immediately be familiar and consistent, which is fantastic. On the other hand, you should think about whether performing CRUD operations on resources is the best approach for your use case.

Here’s an idea on how you could assess the CRUD paradigm’s applicability for your API. First, see if you can name one or more resources or things, for example, files, documents, appointments, contacts, tasks, etc… Then, put them into the following sentence: “Using my API, users can create, read, update and delete $THINGs.” If you feel that this sentence is a good summary of your API, go for it! If you think it captures the essence of your API, but some part is missing, for example, because users can do a multitude of other actions on the resources, you can still use the CRUD paradigm and bolt on those other actions. We’ll discuss this in the section about URL design. If the whole phrase feels off, another design paradigm could be better suited. For example, the RPC (Remote Procedure Call) approach means that you think of your API in terms of executing commands instead of performing actions on resources.

One more remark: many developers think that CRUD is necessary for your API to be RESTful. That is a common misconception. These terms describe different aspects of API design. However, CRUD and REST work nicely together.

Create a new Web API project

  Step 2   Open Visual Studio and create a new project.   

  Step 3   Change the name to CrudUsingReact.  

  Step 4   Choose the template as Web API.  

  Step 5   Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.  

  Step 6   Click on the «ADO.NET Entity Data Model» option and click «Add».  

  Step 7   Select EF Designer from the database and click the «Next» button.  

  Step 8   Add the connection properties and select database name on the next page and click OK.  

  Step 9   Check the «Table» checkbox. The internal options will be selected by default. Now, click the «Finish» button.  

  Step 10   Right-click on Models folder and add two classes — Student and Response respectively. Now, paste the following codes in these classes.

  1. publicclass Student  
  2.    {  
  3.        public string Name { get; set; }  
  4.        public string Rollno { get; set; }  
  5.        public string Class { get; set; }  
  6.        public string Address { get; set; }  
  7.    }  
  1. publicclass Response  
  2.    {  
  3.        public string Status { get; set; }  
  4.        public string Message { get; set; }  
  5.    }  

Step 11   Right-click on the Controllers folder and add a new controller. Name it as «Student controller» and add the following namespace in the Student controller.

  1. using CrudUsingReact.Models;  

Step 12   Now, add a method to insert and update data into the database.

  1.        public object AddotrUpdatestudent(Student st)  
  2.        {  
  3.            try
  4.            {  
  5.                if (st.Id == 0)  
  6.                {  
  7.                    studentmaster sm = new studentmaster();  
  8.                    sm.Name = st.Name;  
  9.                    sm.RollNo = st.Rollno;  
  10.                    sm.Address = st.Address;  
  11.                    sm.Class = st.Class;  
  12.                    DB.studentmasters.Add(sm);  
  13.                    DB.SaveChanges();  
  14.                    returnnew Response  
  15.                    {  
  16.                        Status = «Success»,  
  17.                        Message = «Data Successfully»
  18.                    };  
  19.                }  
  20.                else
  21.                {  
  22.                    var obj = DB.studentmasters.Where(x => x.Id == st.Id).ToList().FirstOrDefault();  
  23.                    if (obj.Id > 0)  
  24.                    {  
  25.                        obj.Name = st.Name;  
  26.                        obj.RollNo = st.Rollno;  
  27.                        obj.Address = st.Address;  
  28.                        obj.Class = st.Class;  
  29.                        DB.SaveChanges();  
  30.                        returnnew Response  
  31.                        {  
  32.                            Status = «Updated»,  
  33.                            Message = «Updated Successfully»
  34.                        };  
  35.                    }  
  36.                }  
  37.            }  
  38.            catch (Exception ex)  
  39.            {  
  40.                Console.Write(ex.Message);  
  41.            }  
  42.            returnnew Response  
  43.            {  
  44.                Status = «Error»,  
  45.                Message = «Data not insert»
  46.            };  
  47.        }  

Step 13   Add other methods to delete and fetch data respectively from the database.

  1.       public object Deletestudent(int id)  
  2.       {  
  3.           var obj = DB.studentmasters.Where(x => x.Id == id).ToList().FirstOrDefault();  
  4.           DB.studentmasters.Remove(obj);  
  5.           DB.SaveChanges();  
  6.           returnnew Response  
  7.           {  
  8.               Status = «Delete»,  
  9.               Message = «Delete Successfuly»
  10.           };  
  11.       }  
  1.       public object   Studentdetails()  
  2.       {  
  3.               var a = DB.studentmasters.ToList();  
  4.               return a;  
  5.       }  

Complete Student controller code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using CrudUsingReact.Models;  
  8. namespace CrudUsingReact.Controllers  
  9. {  
  10.     [RoutePrefix(«Api/Student»)]  
  11.     publicclass studentController : ApiController  
  12.     {  
  13.         CrudDemoEntities DB = new CrudDemoEntities();  
  14.         publicobject AddotrUpdatestudent(Student st)  
  15.         {  
  16.             try
  17.             {  
  18.                 if (st.Id == 0)  
  19.                 {  
  20.                     studentmaster sm = new studentmaster();  
  21.                     sm.Name = st.Name;  
  22.                     sm.RollNo = st.RollNo;  
  23.                     sm.Address = st.Address;  
  24.                     sm.Class = st.Class;  
  25.                     DB.studentmasters.Add(sm);  
  26.                     DB.SaveChanges();  
  27.                     returnnew Response  
  28.                     {  
  29.                         Status = «Success»,  
  30.                         Message = «Data Successfully»
  31.                     };  
  32.                 }  
  33.                 else
  34.                 {  
  35.                     var obj = DB.studentmasters.Where(x => x.Id == st.Id).ToList().FirstOrDefault();  
  36.                     if (obj.Id > 0)  
  37.                     {  
  38.                         obj.Name = st.Name;  
  39.                         obj.RollNo = st.RollNo;  
  40.                         obj.Address = st.Address;  
  41.                         obj.Class = st.Class;  
  42.                         DB.SaveChanges();  
  43.                         returnnew Response  
  44.                         {  
  45.                             Status = «Updated»,  
  46.                             Message = «Updated Successfully»
  47.                         };  
  48.                     }  
  49.                 }  
  50.             }  
  51.             catch (Exception ex)  
  52.             {  
  53.                 Console.Write(ex.Message);  
  54.             }  
  55.             returnnew Response  
  56.             {  
  57.                 Status = «Error»,  
  58.                 Message = «Data not insert»
  59.             };  
  60.         }  
  61.         publicobject   Studentdetails()  
  62.         {  
  63.                 var a = DB.studentmasters.ToList();  
  64.                 return a;  
  65.         }  
  66.         publicobject StudentdetailById(int id)  
  67.         {  
  68.             var obj = DB.studentmasters.Where(x => x.Id == id).ToList().FirstOrDefault();  
  69.             return obj;  
  70.         }  
  71.         publicobject Deletestudent(int id)  
  72.         {  
  73.             var obj = DB.studentmasters.Where(x => x.Id == id).ToList().FirstOrDefault();  
  74.             DB.studentmasters.Remove(obj);  
  75.             DB.SaveChanges();  
  76.             returnnew Response  
  77.             {  
  78.                 Status = «Delete»,  
  79.                 Message = «Delete Successfuly»
  80.             };  
  81.         }  
  82.     }  
  83. }  

Step 14   Now, let’s enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the «Microsoft.Asp.Net.WebApi.Cors» package. Open Webapiconfig.cs and add the following lines.

  1. EnableCorsAttribute cors = new EnableCorsAttribute(«*», «*», «*»);    
  2. config.EnableCors(cors);   

🔗 URL Design Best Practices

As we’ve established before, URLs describe resources whereas HTTP verbs describe actions that can be taken upon them. That leads us to the first rule of CRUD URL design: URLs should contain only nouns, never verbs, unless you are deliberately adding something to your API that doesn’t fit the CRUD paradigm.

The nouns in URLs are the same that describe your domain model. When modeling your domain, pay attention to the following:

  • Do not make nouns unnecessarily long and complicated (, not ).
  • Use common terminology ( instead of ).

Apart from the noun rules, there are a few other best practices that the industry has established and many companies have put down in their API style guides:

  • Use lowercase ( not ) to avoid the ambiguity around URL case-sensitivity.
  • For individual resources, include resource identifiers in the path, not the query ( instead of ).
  • Paths that end with a resource name (and typically no trailing slash) are used to list multiple items () or create items without specifying an identifier.
  • Paths can indicate a hierarchy of subresources (), but API designers should avoid complex structures that require more than two levels of nesting.
  • Nouns should be in the plural form ( instead of ) unless they describe a singleton.
  • Nouns that are compounds of multiple words should use a hyphen as a separator (). There’s a very mundane reason for this: when URLs are hyperlinks, they are often underlined, which would render an underscore separator invisible.
  • URLs should never reveal the underlying implementation ( not ).
  • The query part of the URL is for search and filtering and commonly used with a resource list endpoint ().

Now, let’s have a look at the more controversial issues:


Many APIs add a version prefix to their paths (). While this is undoubtedly an easy way for clients to convey their preference for a specific API version, URL design purists might argue that this is not part of the resource and therefore doesn’t belong in the URL. They prefer configuring versioning as part of the account, sending the information as an HTTP header or building the API in a backward-compatible way so that it does not require versioning at all. As versioning is a whole different topic unto itself that depends on the full API lifecycle in your project, I won’t recommend one way over the other here.

Resource Types

Occasionally, API developers add a suffix to their paths to indicate the serialization format of a resource (). Newer APIs that do not require other serializations such as XML for legacy reasons go all-in on the JSON bandwagon. Therefore, if you don’t expect to support anything other than JSON anyway, the in the URL becomes redundant. And even if you do, down the line, there’s an alternative: the HTTP Accept header. On the other hand, if offering resources to less experienced developers in formats like CSV is one of your use cases, these developers will greatly appreciate being able to replace with instead of fiddling with HTTP headers.

Non-CRUD Actions

The four words create, read, update, delete don’t necessarily suffice to describe all actions that can be taken upon resources. For example, you might want to block or suspend a user, which is different from deleting them.

It is often possible to map these to update actions, for example, updating a user with a status attribute set to suspended, but in other instances, this could feel clunky and forced.

In those cases, it makes sense to include actions as resources and place them at URLs such as . It’s a great idea to denote them clearly, e.g., by prefixing them with , although the use of a verb (like “suspend”) already gives it away that we’re breaking away from pure CRUD for better developer experience.

What is CRUD?

CRUD – again is:

  • Create
  • Read
  • Update
  • Delete

is shorthand for the basic functions that an application must conventionally be able to fulfill in order to be considered “complete.”

For example, let’s consider a basic phone book app. In order to feel like a “finished” application, the user should be able to do at least four things: create new entries, access the information available for each entry, modify and save the existing information, and remove old and unnecessary entries from the book. In this example, the phone book is essentially functioning as a database, and it’s no coincidence that the term CRUD is generally used to describe what an application with a database should conventionally do.

Because these four functions are so universal to programming, each of the elements of CRUD is represented in virtually every single programming language out there that deals with databases. A query language like SQL may call their Create function an INSERT, and a web application using HTTP may make a POST request, but both of these things are simply telling a database somewhere to produce a new entry. Same goes with reading, updating, and deleting items in a database – these are universal necessities, and although different languages may handle them differently, you can always be assured that any application dealing with a table of information will need to have these four key capabilities.

Ubah fungsi callback dari onPressed Button

Sekarang kita ubah isi dari callback onPressed Button-nya menjadi seperti berikut.

if (_isFieldNameValid == null ||_isFieldEmailValid == null ||_isFieldAgeValid == null ||    !_isFieldNameValid ||    !_isFieldEmailValid ||    !_isFieldAgeValid) {  _scaffoldState.currentState.showSnackBar(    SnackBar(      content: Text("Please fill all field"),    ),  );return;}setState(() => _isLoading = true);String name = _controllerName.text.toString();String email = _controllerEmail.text.toString();int age = int.parse(_controllerAge.text.toString());Profile profile =    Profile(name: name, email: email, age: age);if (widget.profile == null) {_apiService.createProfile(profile).then((isSuccess) {    setState(() => _isLoading = false);if (isSuccess) {      Navigator.pop(_scaffoldState.currentState.context);    } else {      _scaffoldState.currentState.showSnackBar(SnackBar(        content: Text("Submit data failed"),      ));    }  });} else {  profile.id = widget.profile.id;_apiService.updateProfile(profile).then((isSuccess) {    setState(() => _isLoading = false);if (isSuccess) {      Navigator.pop(_scaffoldState.currentState.context);    } else {      _scaffoldState.currentState.showSnackBar(SnackBar(        content: Text("Update data failed"),      ));    }  });}

Sekarang coba test jalankan fitur ubah datanya.

Fitur ubah data

Hapus Data

Untuk membuat fitur hapus data kita perlu menambahkan satu fungsi di file api_service.dart seperti berikut.

Future<bool> deleteProfile(int id) async {final response = await client.delete("$baseUrl/api/profile/$id",    headers: {"content-type": "application/json"},  );if (response.statusCode == 200) {return true;  } else {return false;  }}

Sekarang kita buka file home_screen.dart dan silakan lakukan beberapa perubahan berikut.

6. Configure H2 Database

By default, Spring Boot configures the application to connect to an in-memory store with the username sa and an empty password. However, we can change those parameters by adding the following properties to the application.properties file:


By design, the in-memory database is volatile and data will be lost when we restart the application.

We can change that behavior by using file-based storage. To do this we need to update the spring.datasource.url:


In this example, we will use a default configuration of the H2 database (we don’t use the above configuration, the above configuration is just to know more about H2 database configuration with Spring boot).

Маршруты и Эндпоинты

  • Маршрут (Route — роут) — это «имя», которое отсылает работу API к определенным эндпоинтам. Если упростить, то можно сказать, что маршрут — это URL к которому можно обратиться разными HTTP методами. Маршрут может иметь несколько эндпоинтов.

  • Эндпоинт (Endpoint — конечная точка) — это само обращение к маршруту отдельным HTTP методом. Эндпоинт выполняют конкретную задачу, принимают параметры и возвращают данные Клиенту.
Разберем URL


  • Здесь — это маршрут, а — это базовый путь самого REST API.
  • Этот маршрут имеет 3 эндпоинта:
    • GET — запускает метод и возвращает данные поста Клиенту.
    • PUT|PATCH|POST — запускает метод , обновляет данные и возвращает их Клиенту.
    • DELETE — запускает метод , удаляет пост и возвращает только что удаленные данные Клиенту.
Запрос к корневому маршруту

Если сделать GET запрос к корневому маршруту , мы получим JSON ответ, в котором видно какие доступны маршруты, и какие доступны эндпоинты для каждого из них. При этом маршрут тут это (корень), а при GET запросе он становится эндпоинтом (конечной точкой).

Маршрут без ЧПУ

На сайтах без ЧПУ маршрут (с претворяющем слэшем) добавляется в URL как значение параметра . Например:

  • http://example.com/?rest_route=/ — корневой маршрут.
  • http://example.com/?rest_route=/wp/v2/posts/123 — получение поста 123.

Add Student Attendance (Create)

For taking the student attendance data from the user, the list of all students will be displayed with radio options. These buttons will be used to select present/absent accordingly.

The following code is used to show the attendance add-form to the user. In this form, the attendance date is a required field.

By default, the radio options are selected as “present”. We can change it accordingly based on the student attendance status.

<?php require_once "web/header.php"; ?>

<form name="frmAdd" method="post" action="" id="frmAdd"
    onSubmit="return validate();">
        <input type="date" name="attendance_date" id="attendance_date" class="demoInputBox"> <span id="attendance_date-info" class="info"></span>
    <div id="toys-grid">
        <table cellpadding="10" cellspacing="1">

            if (! empty($studentResult)) {
                foreach ($studentResult as $k => $v) {
                    <td><input type="hidden"
            name="student_id[]" id="student_id" value = "<?php echo $studentResult; ?>">
            <?php echo $studentResult; ?></td>
                    <td><input type="radio" name="attendance-<?php echo $studentResult; ?>" value="present" checked /></td>
                    <td><input type="radio" name="attendance-<?php echo $studentResult; ?>" value="absent" /></td>
        <input type="submit" name="add" id="btnSubmit" value="Add" />
<script src="https://code.jquery.com/jquery-2.1.1.min.js"
function validate() {
    var valid = true;   
    if(!$("#attendance_date").val()) {
        valid = false;
    return valid;

The following screenshot shows the student attendance add form with a selectable date and attendance radio options.

11. Running Application

This spring boot application has an entry point Java class called Application.java with the public static void main(String[] args) method, which you can run to start the application.

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

@SpringBootApplication is a convenience annotation that adds all of the following:

  • @Configuration tags the class as a source of bean definitions for the application context.

  • @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.

  • Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.

  • @ComponentScan tells Spring to look for other components, configurations, and services in the hello package, allowing it to find the controllers.


If you’ve ever dabbled in developing a website or an app, it’s possible that you’ve come across another acronym that sounds awfully similar to what we’re describing with CRUD. REST (Representational State Transfer), or RESTful programming, is another term that deals with how a developer might deal with the manipulation of information coming into and out of a program. However, these two concepts deal with very different levels of programming and actually don’t compete against each other so much as complement one another.

CRUD, at its roots, is a basic and primitive way of manipulating information. It’s what an application pretty much HAS to be able to do, rather than a way of going about doing it. REST, on the other hand, is a high-level way of creating, changing and removing information for the user. Specifically, REST refers to manipulating data through HTTP commands, and an ideology for how to streamline the relationship between the data that a user is manipulating on screen and the information that is saved on the server. A programmer can create a REST API that handles basic CRUD functions, but building a CRUD application in no way insinuates the use of RESTful programming.

Hopefully, this has been an insightful look at what CRUD means to programmers, how applications might handle those functions, and what exactly the difference is between CRUD and REST when it comes to creating an application.

Create Data

Setelah selesai dengan fitur menampilkan list data sekarang kita buat fitur untuk menambahkan data dimana, untuk menambahkan data kita bisa melakukannya lewat action di appbar yang mana ketika kita tap action tersebut app akan menuju ke form tambah data. Untuk itu, kita perlu buat dulu seperti berikut.

final GlobalKey<ScaffoldState> _scaffoldState = GlobalKey<ScaffoldState>();class FormAddScreen extends StatefulWidget {  @override  _FormAddScreenState createState() => _FormAddScreenState();}class _FormAddScreenState extends State<FormAddScreen> {  bool _isLoading = false;  ApiService _apiService = ApiService();  bool _isFieldNameValid;  bool _isFieldEmailValid;  bool _isFieldAgeValid;  TextEditingController _controllerName = TextEditingController();  TextEditingController _controllerEmail = TextEditingController();  TextEditingController _controllerAge = TextEditingController();  @override  Widget build(BuildContext context) {return Scaffold(      key: _scaffoldState,      appBar: AppBar(        iconTheme: IconThemeData(color: Colors.white),        title: Text(          "Form Add",          style: TextStyle(color: Colors.white),        ),      ),      body: Stack(        children: <Widget>,                  ),                )              ],            ),          ),          _isLoading              ? Stack(                  children: <Widget>,                )              : Container(),        ],      ),    );  }  Widget _buildTextFieldName() {return TextField(      controller: _controllerName,      keyboardType: TextInputType.text,      decoration: InputDecoration(        labelText: "Full name",        errorText: _isFieldNameValid == null || _isFieldNameValid            ? null: "Full name is required",      ),      onChanged: (value) {        bool isFieldValid = value.trim().isNotEmpty;if (isFieldValid != _isFieldNameValid) {          setState(() => _isFieldNameValid = isFieldValid);        }      },    );  }  Widget _buildTextFieldEmail() {return TextField(      controller: _controllerEmail,      keyboardType: TextInputType.emailAddress,      decoration: InputDecoration(        labelText: "Email",        errorText: _isFieldEmailValid == null || _isFieldEmailValid            ? null: "Email is required",      ),      onChanged: (value) {        bool isFieldValid = value.trim().isNotEmpty;if (isFieldValid != _isFieldEmailValid) {          setState(() => _isFieldEmailValid = isFieldValid);        }      },    );  }  Widget _buildTextFieldAge() {return TextField(      controller: _controllerAge,      keyboardType: TextInputType.number,      decoration: InputDecoration(        labelText: "Age",        errorText: _isFieldAgeValid == null || _isFieldAgeValid            ? null: "Age is required",      ),      onChanged: (value) {        bool isFieldValid = value.trim().isNotEmpty;if (isFieldValid != _isFieldAgeValid) {          setState(() => _isFieldAgeValid = isFieldValid);        }      },    );  }}

Pada kode diatas, kita membuat widget setiap terpisah (dalam bentuk method) dimana, ini bertujuan agar lebih gampang membaca kode-nya.

Form Add Data

Pada didalam callback kita menuliskan kode untuk melakukan post data ke API. Jadi, untuk melakukan post data ke API kita menerapkan logic seperti berikut.

  • Kita cek terlebih dahulu apakah semua field sudah valid atau belum.
  • Lalu, kita ambil nilai setiap field.
  • Kemudian, kita bungkus setiap data field tadi kedalam bentuk objek
  • Lalu, kita ubah objek tadi ke bentuk json dengan cara menggunakan method .

Dan berikut kode yang melakukan tugas tersebut.

child: RaisedButton(  onPressed: () {if (_isFieldNameValid == null ||        _isFieldEmailValid == null ||        _isFieldAgeValid == null ||        !_isFieldNameValid ||        !_isFieldEmailValid ||        !_isFieldAgeValid) {      _scaffoldState.currentState.showSnackBar(        SnackBar(          content: Text("Please fill all field"),        ),      );return;    }    setState(() => _isLoading = true);    String name = _controllerName.text.toString();    String email = _controllerEmail.text.toString();    int age = int.parse(_controllerAge.text.toString());    Profile profile =        Profile(name: name, email: email, age: age);    _apiService.createProfile(profile).then((isSuccess) {      setState(() => _isLoading = false);if (isSuccess) {        Navigator.pop(_scaffoldState.currentState.context);      } else {        _scaffoldState.currentState.showSnackBar(SnackBar(          content: Text("Submit data failed"),        ));      }    });  },  child: Text(    "Submit".toUpperCase(),    style: TextStyle(      color: Colors.white,    ),  ),  color: Colors.orange,)

Kemudian, jangan lupa kita juga perlu menambahkan fungsi di dalam file seperti berikut.

Future<bool> createProfile(Profile data) async {final response = await client.post(    "$baseUrl/api/profile",    headers: {"content-type": "application/json"},    body: profileToJson(data),  );if (response.statusCode == 201) {return true;  } else {return false;  }}

Dan berikut ialah output programnya.


To create a new CRUD service API, simply bootstrap the application by injecting the dependencies as depicted in the example below.

import{server,mysqlConnect,mongooseConnect,config}from'@ctt/crud-api';import{schemaasmongooseSchema}from'./persistence/mongoose/schema';importroutesfrom'./routes';importservicesfrom'./services';import{Server}from'hapi';constapplication=()Promise<Server>=>server({dbConnectmongooseConnect,schemamongooseSchema,config,routes,services,swaggerOptions{tags{'users''Operation for handling user records'},info{title'Microservice CRUD API Server',description'Powering Craft Turf\'s microservice projects',version'0.0.1'}},swaggerUiOptions{title'My API',path'/docs',swaggerOptions{validatorUrlnull}},});

Then start the app as shown in the example below

(async()Promise<void>=>{constapp=awaitapplication();awaitapp.start();app.log('App runninng on',app.info.uri);})();

PHP CRUD Engine using Model View Controller (MVC)

In this example, the landing page index.php will be the CRUD action controller. In this controller, the student and the attendance CRUD action cases are stacked by using PHP switch control structure.

The actions parameter is passed with the URL based on which the controller case will be executed. The model classes Student.php and Attendance.php are consisting of CRUD functions which will be called from the appropriate CRUD cases.

The model class functions are preparing the query and query parameters array. The query and its parameters are sent on invoking the appropriate database functions.

In the DBController class, the query statements are executed after binding the query parameters using MySQLi.

The control flow through the landing controller -> model -> DBController will be used to get the dynamic results. The dynamic results are rendered on the presentation layer which is created in the template files.

This essentially summarizes the MVC architecture and the flow of control between the different layers involved in the implementation.


Это PHP класс созданный по разработанному разработчиками WP стандарту .

Классы контроллеров объединяют отдельные части REST API в единый механизм. В них должны создаваться маршруты, они должны обрабатывать запросы, генерировать ответы API и описывать схему ресурса.

Концепция контроллера принята в рамках WP-API для того, чтобы иметь стандартный шаблон для классов контроллера — классов представляющих ресурсы (конечные точки). Шаблоном класса контроллера является абстрактный класс WP_REST_Controller. Каждый класс контроллера должен иметь аналогичную схему методов, сделано так для того, чтобы все конечные точки имели одинаковые названия PHP методов.

Подробнее читайте в разделе Классы контроллеров!

С этим читают