Quickstarters
Feature Overview
How to Build a Backend for Yii 2?
40 min
introduction in this tutorial, you will learn how to build a backend for yii 2 using back4app yii 2 is a popular open source php framework that helps you create secure and efficient web applications by integrating the yii framework with back4app, you can take advantage of powerful features such as database management, cloud functions, rest and graphql apis, user authentication, and real time queries – all while speeding up your backend development process you will see how to leverage back4app’s environment to cut down on manual server configuration, letting you focus on writing your yii 2 code by following these steps, you will gain hands on experience with essential functionalities, including robust security controls (acls, clps), scheduling recurring tasks, and setting up external integrations via webhooks by the end of this tutorial, you will have a solid backend structure in place for your yii 2 project, ready to scale into production or enhance with custom business logic you will also be well prepared to integrate third party apis or build new features into your web applications prerequisites to complete this tutorial, you will need a back4app account and a new back4app project getting started with back4app https //www back4app com/docs/get started/new parse app if you do not have an account, sign up for free and follow the linked guide to get your project ready a local yii 2 development environment you can download yii 2 using composer https //getcomposer org/ and follow the yii 2 official guide https //www yiiframework com/doc/guide/2 0/en for setup php (version 7 4 or above) installed you’ll need a compatible php environment to run yii 2 and manage composer packages familiarity with php and basic yii 2 concepts if you are new to the yii framework, check out the official yii 2 documentation https //www yiiframework com/doc/guide/2 0/en make sure you have all of these prerequisites in place before you begin having your back4app project set up and your local yii 2 environment ready will allow you to follow along more easily step 1 – creating a new project on back4app and connecting create a new project the first step to build a backend for yii 2 is to create a new back4app project if you haven’t already done so, follow these steps log in to your back4app account click the “new app” button in your back4app dashboard name your app (e g , “yii2 backend tutorial”) once the project is created, you will see it on your back4app dashboard this serves as the foundation for all backend configurations we will explore in this tutorial connecting via parse apis back4app uses the parse platform under the hood while the parse php sdk exists, you can also integrate your yii 2 application with back4app using parse’s rest or graphql apis this approach is flexible, letting you write code that sends http or graphql requests to back4app from your yii controllers or models retrieve your parse keys in your back4app dashboard, go to your app’s “app settings” or “security & keys” locate your application id , rest api key , and the parse server url (usually https //parseapi back4app com ) keep these credentials close at hand you will need them when making requests from your yii 2 application to back4app step 2 – setting up the database your back4app project comes with a cloud based database that is automatically managed by the parse server you can create a data model and store objects in it using rest, graphql, or the ai agent in back4app creating a data model open the “database” section in your back4app dashboard create a new class (e g , “todo”) and add columns such as title (string) and iscompleted (boolean) you can also let parse create these columns automatically the first time your yii code sends data furthermore, back4app’s ai agent can help you set up the schema open the ai agent from your app dashboard or the menu describe your data model (e g , “create a todo app schema with a todo class”) allow the ai agent to generate the schema reading and writing data using rest api below is an example of saving a todo object using the rest api you might implement this in a yii 2 controller action using curl or php’s file get contents() to post json data curl x post \\ h "x parse application id your application id" \\ h "x parse rest api key your rest api key" \\ h "content type application/json" \\ d '{"title" "buy groceries", "iscompleted" false}' \\ https //parseapi back4app com/classes/todo example yii 2 php code snippet (using curl) in a controller public function actioncreatetodo() { $url = "https //parseapi back4app com/classes/todo"; $data = \[ "title" => "buy groceries", "iscompleted" => false ]; $headers = \[ "x parse application id your application id", "x parse rest api key your rest api key", "content type application/json" ]; $ch = curl init($url); curl setopt($ch, curlopt post, 1); curl setopt($ch, curlopt postfields, json encode($data)); curl setopt($ch, curlopt httpheader, $headers); curl setopt($ch, curlopt returntransfer, true); $result = curl exec($ch); curl close($ch); // handle $result as needed, e g , parse json or redirect } querying the same data with rest might look like curl x get \\ h "x parse application id your application id" \\ h "x parse rest api key your rest api key" \\ https //parseapi back4app com/classes/todo reading and writing data using graphql api you can also create and read data using parse’s graphql interface for instance, to create a todo mutation { createtodo(input { fields { title "clean the house" iscompleted false } }) { todo { objectid title iscompleted } } } in yii 2, you can use graphql libraries https //packagist org/packages/webonyx/graphql php or simple http requests to interact with the back4app graphql endpoint https //parseapi back4app com/graphql working with live queries (optional) for real time updates, back4app supports live queries , which let you subscribe to changes on a class although typical use in yii 2 might be less common, you can still enable live queries in your back4app settings and handle websocket connections in php this is more advanced, so refer to the parse live queries documentation https //www back4app com/docs/javascript live queries/parse livequery overview for details on implementing real time features in your php based web applications step 3 – applying security with acls and clps brief overview back4app offers access control lists (acls) and class level permissions (clps) to protect your data acls apply to specific objects, while clps define global permissions for each class setting up class level permissions go to database in your back4app dashboard and select the class (e g , “todo”) open the clps tab , and configure read/write permissions (e g , “requires authentication” or “no access”) configuring acls you can set acls for individual objects by including an acl field when creating or updating data via rest or graphql for example, using rest curl x post \\ h "x parse application id your application id" \\ h "x parse rest api key your rest api key" \\ h "content type application/json" \\ d '{ "title" "private todo", "acl" { "user object id here" { "read" true, "write" true }, " " { "read" false, "write" false } } }' \\ https //parseapi back4app com/classes/todo this object can now only be accessed by the user with the specified objectid step 4 – writing cloud code functions why cloud code using cloud code on back4app allows you to run custom server side logic without managing your own servers you can create business logic , data validations , or triggers for object creation, updates, and deletions example cloud code function below is a simple cloud code function (written in javascript) that calculates text length main js // main js parse cloud define('calculatetextlength', async (request) => { const { text } = request params; if (!text) { throw new error('no text provided'); } return { length text length }; }); deployment you can deploy your cloud code via the back4app cli or directly in the cloud code > functions section of your back4app dashboard back4app cli dashboard copy/paste your code into main js and click deploy calling your cloud function you can call your function from yii 2 using a simple rest post request curl x post \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ h "content type application/json" \\ d '{"text" "hello back4app"}' \\ https //parseapi back4app com/functions/calculatetextlength or via graphql mutation { calculatetextlength(input { text "hello graphql" }) { result } } step 5 – configuring authentication user authentication in back4app back4app uses the parse user class as a foundation for secure authentication you can create and verify users through rest or graphql calls creating a user with rest curl x post \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ h "content type application/json" \\ d '{ "username" "alice", "password" "secret123", "email" "alice\@example com" }' \\ https //parseapi back4app com/users logging in a user curl x get \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ g \\ \ data urlencode 'username=alice' \\ \ data urlencode 'password=secret123' \\ https //parseapi back4app com/login social login for social logins (google, apple, facebook, etc ), configure your oauth settings in back4app and your yii 2 application to handle the necessary tokens refer to back4app’s social login docs https //www back4app com/docs/platform/sign in with apple for provider specific guidelines email verification & password reset enable email verification and password reset in the email settings of your back4app dashboard to improve user security go to email settings in your back4app dashboard enable email verification and customize your email templates test that your emails are sent and received properly step 6 – handling file storage back4app provides secure file storage via the parse file system while the parse php sdk is an option, we’ll illustrate rest again for consistency uploading files via rest curl x post \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ h "content type image/png" \\ \ data binary "@path/to/local/image png" \\ https //parseapi back4app com/files/myimage png this returns a url for the saved file you can then store that url in a class (like photo ) for later retrieval file security considerations you can limit file uploads to only authenticated users or to specific roles by configuring parse server settings in your app for more granular control, combine these settings with your acl and clp rules step 7 – email verification and password reset overview email verification ensures users own the email addresses they register with, and password reset allows them to recover accounts back4app dashboard configuration enable email verification under app settings > email settings customize the “from” address and email templates test by creating a new user to confirm the verification email is sent implementation in your yii 2 application, direct users to a route that triggers parse’s password reset endpoint https //www back4app com/docs/users/password reset the rest of the flow (like sending the actual email) is handled by the back4app infrastructure step 8 – scheduling tasks with cloud jobs what cloud jobs do cloud jobs in back4app let you schedule routine tasks, such as cleaning data or sending notifications define them in your cloud code ( main js ) and schedule them in the dashboard example cleanup job main js parse cloud job('cleanupoldtodos', async (request) => { const todo = parse object extend('todo'); const query = new parse query(todo); const now = new date(); const thirty days = 30 24 60 60 1000; const cutoff = new date(now thirty days); query lessthan('createdat', cutoff); try { const oldtodos = await query find({ usemasterkey true }); await parse object destroyall(oldtodos, { usemasterkey true }); return `deleted ${oldtodos length} old todos `; } catch (err) { throw new error('error during cleanup ' + err message); } }); step 9 – integrating webhooks definition webhooks allow your back4app application to send automated http requests to external services when events occur, like creating a new todo configuration in your back4app dashboard , go to more > webhooks add a webhook endpoint (e g , https //your external service com/webhook ) configure triggers (e g , “new record in todo class”) with webhooks, you can send notifications to other services (like slack, stripe, or your custom api) whenever a todo object is created or updated step 10 – exploring the back4app admin panel where to find it the back4app admin app is a point and click interface for managing your data without writing code you can enable it by visiting app dashboard > more > admin app and then enable admin app features after creating an admin user, you’ll have a dedicated subdomain for your admin app this gives authorized team members a clean interface for crud operations on your back4app database, reviewing logs, or viewing analytics — no code needed conclusion in this tutorial, you discovered how to build a backend for yii 2 using back4app you configured a cloud based database, set up robust security with acls and clps, scheduled background tasks with cloud jobs, and integrated external services through webhooks you also saw how to manage user authentication and file storage securely having combined an open source yii framework for building web applications with back4app’s scalable infrastructure, you now have a potent environment ready for development and growth next steps move toward production by expanding your data models, applying additional security settings, and optimizing performance integrate external apis (payment gateways, email providers) via cloud code or direct webhooks explore official back4app docs for deeper topics like advanced security, log analysis, and performance optimizations learn more about building complex web applications with yii 2 by using role based access control, caching strategies, and advanced database relationships with this foundation, you can continue to enhance your yii 2 project, focus on business specific logic, and deliver robust, scalable functionality for your users enjoy coding and building modern web applications