In the last part, we learned about Neo4j and how to use it with PHP. In this post, we’ll be using that knowledge to build a real Silex-powered social network application with a graph database.
I’ll use Silex, Twig, Bootstrap and NeoClient to build the application.
Create a directory for the app. I named mine spsocial.
Add these lines to your composer.json and run composer install to install the dependencies :
<span>{ </span> <span>"require": { </span> <span>"silex/silex": "~1.1", </span> <span>"twig/twig": ">=1.8,<2.0-dev", </span> <span>"symfony/twig-bridge": "~2.3", </span> <span>"neoxygen/neoclient": "~2.1" </span> <span>}, </span> <span>"autoload": { </span> <span>"psr-4": { </span> <span>"Ikwattro\SocialNetwork\": "src" </span> <span>} </span> <span>} </span><span>}</span>
You can download and install Bootstrap to the web/assets folder of your project.
You can find the bootstrap demo app here as well: https://github.com/sitepoint-editors/social-network
We need to configure Silex and declare Neo4jClient so it will be available in the Silex Application. Create an index.php file in the web/ folder of your project :
<span><span><?php </span></span><span> </span><span><span>require_once __DIR__.'/../vendor/autoload.php'; </span></span><span> </span><span><span>use Neoxygen<span>\NeoClient\ClientBuilder</span>; </span></span><span> </span><span><span>$app = new Silex<span>\Application</span>(); </span></span><span> </span><span><span>$app['neo'] = $app->share(function(){ </span></span><span> <span>$client = ClientBuilder<span>::</span>create() </span></span><span> <span>->addDefaultLocalConnection() </span></span><span> <span>->setAutoFormatResponse(true) </span></span><span> <span>->build(); </span></span><span> </span><span> <span>return $client; </span></span><span><span>}); </span></span><span> </span><span><span>$app->register(new Silex<span>\Provider\TwigServiceProvider</span>(), array( </span></span><span> <span>'twig.path' => __DIR__.'/../src/views', </span></span><span><span>)); </span></span><span><span>$app->register(new Silex<span>\Provider\MonologServiceProvider</span>(), array( </span></span><span> <span>'monolog.logfile' => __DIR__.'/../logs/social.log' </span></span><span><span>)); </span></span><span><span>$app->register(new Silex<span>\Provider\UrlGeneratorServiceProvider</span>()); </span></span><span> </span><span><span>$app->get('/', 'Ikwattro\SocialNetwork\Controller\WebController::home') </span></span><span> <span>->bind('home'); </span></span><span> </span><span><span>$app->run();</span></span>
Twig is configured to have its template files located in the src/views folder.
A home route pointing to / is registered and configured to use the WebController we will create later.
The application structure should look like this :
Note that here I used bower to install bootstrap, but it is up to you what you want to use.
The next step is to create our base layout with a content block that our child Twig templates will override with their own content.
I’ll take the default bootstrap theme with a navbar on top:
<span><!DOCTYPE html> </span><span><html lang="en"> </span><span><head> </span> <span><meta charset="utf-8"> </span> <span><meta http-equiv="X-UA-Compatible" content="IE=edge"> </span> <span><meta name="viewport" content="width=device-width, initial-scale=1"> </span> <span><meta name="description" content=""> </span> <span><meta name="author" content=""> </span> <span><title>My first Neo4j application</title> </span> <span><!-- Bootstrap core CSS --> </span> <span><link href="{{ app.request.basepath }}/assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> </span> <span><!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> </span> <span><!--[if lt IE 9]> </span> <span><script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> </span> <span><script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> </span> <span><![endif]--> </span> <span><style> </span> body <span>{ padding-top: 70px; } </span> <span></style> </span><span></head> </span><span><body> </span> <span><div class="navbar navbar-inverse navbar-fixed-top" role="navigation"> </span> <span><div class="container"> </span> <span><div class="navbar-header"> </span> <span><button type="button" id="collbut" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse"> </span> <span><span class="sr-only">Toggle navigation</span> </span> <span><span class="icon-bar"></span> </span> <span><span class="icon-bar"></span> </span> <span><span class="icon-bar"></span> </span> <span></button> </span> <span><a class="navbar-brand" href="#">My first Neo4j application</a> </span> <span></div> </span> <span></div> </span><span></div> </span> <span><div class="container-fluid"> </span> <span>{% block content %} </span> <span>{% endblock content %} </span> <span></div> </span><span></body> </span><span></html></span>
So far, we have Neo4j available in the application, our base template is created and we want to list all users on the home page.
We can achieve this in two steps :
<span>{ </span> <span>"require": { </span> <span>"silex/silex": "~1.1", </span> <span>"twig/twig": ">=1.8,<2.0-dev", </span> <span>"symfony/twig-bridge": "~2.3", </span> <span>"neoxygen/neoclient": "~2.1" </span> <span>}, </span> <span>"autoload": { </span> <span>"psr-4": { </span> <span>"Ikwattro\SocialNetwork\": "src" </span> <span>} </span> <span>} </span><span>}</span>
The controller shows the process, we retrieve the neo service and issue a Cypher query to retrieve all the users.
The users collection is then passed to the index.html.twig template.
<span><span><?php </span></span><span> </span><span><span>require_once __DIR__.'/../vendor/autoload.php'; </span></span><span> </span><span><span>use Neoxygen<span>\NeoClient\ClientBuilder</span>; </span></span><span> </span><span><span>$app = new Silex<span>\Application</span>(); </span></span><span> </span><span><span>$app['neo'] = $app->share(function(){ </span></span><span> <span>$client = ClientBuilder<span>::</span>create() </span></span><span> <span>->addDefaultLocalConnection() </span></span><span> <span>->setAutoFormatResponse(true) </span></span><span> <span>->build(); </span></span><span> </span><span> <span>return $client; </span></span><span><span>}); </span></span><span> </span><span><span>$app->register(new Silex<span>\Provider\TwigServiceProvider</span>(), array( </span></span><span> <span>'twig.path' => __DIR__.'/../src/views', </span></span><span><span>)); </span></span><span><span>$app->register(new Silex<span>\Provider\MonologServiceProvider</span>(), array( </span></span><span> <span>'monolog.logfile' => __DIR__.'/../logs/social.log' </span></span><span><span>)); </span></span><span><span>$app->register(new Silex<span>\Provider\UrlGeneratorServiceProvider</span>()); </span></span><span> </span><span><span>$app->get('/', 'Ikwattro\SocialNetwork\Controller\WebController::home') </span></span><span> <span>->bind('home'); </span></span><span> </span><span><span>$app->run();</span></span>
The template is very light, it extends our base layout and add an unsorted list with the user’s firstnames and lastnames in the content inherited block.
Start the built-in php server and admire your work :
<span><!DOCTYPE html> </span><span><html lang="en"> </span><span><head> </span> <span><meta charset="utf-8"> </span> <span><meta http-equiv="X-UA-Compatible" content="IE=edge"> </span> <span><meta name="viewport" content="width=device-width, initial-scale=1"> </span> <span><meta name="description" content=""> </span> <span><meta name="author" content=""> </span> <span><title>My first Neo4j application</title> </span> <span><!-- Bootstrap core CSS --> </span> <span><link href="{{ app.request.basepath }}/assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> </span> <span><!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> </span> <span><!--[if lt IE 9]> </span> <span><script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> </span> <span><script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> </span> <span><![endif]--> </span> <span><style> </span> body <span>{ padding-top: 70px; } </span> <span></style> </span><span></head> </span><span><body> </span> <span><div class="navbar navbar-inverse navbar-fixed-top" role="navigation"> </span> <span><div class="container"> </span> <span><div class="navbar-header"> </span> <span><button type="button" id="collbut" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse"> </span> <span><span class="sr-only">Toggle navigation</span> </span> <span><span class="icon-bar"></span> </span> <span><span class="icon-bar"></span> </span> <span><span class="icon-bar"></span> </span> <span></button> </span> <span><a class="navbar-brand" href="#">My first Neo4j application</a> </span> <span></div> </span> <span></div> </span><span></div> </span> <span><div class="container-fluid"> </span> <span>{% block content %} </span> <span>{% endblock content %} </span> <span></div> </span><span></body> </span><span></html></span>
Let’s say now that we want to click on a user, and be presented his detail information and the users he follows.
Step 1 : Create a route in index.php
<span><span><?php </span></span><span> </span><span><span>namespace Ikwattro<span>\SocialNetwork\Controller</span>; </span></span><span> </span><span><span>use Silex<span>\Application</span>; </span></span><span><span>use Symfony<span>\Component\HttpFoundation\Request</span>; </span></span><span> </span><span><span>class WebController </span></span><span><span>{ </span></span><span> </span><span> <span>public function home(Application $application, Request $request) </span></span><span> <span>{ </span></span><span> <span>$neo = $application['neo']; </span></span><span> <span>$q = 'MATCH (user:User) RETURN user'; </span></span><span> <span>$result = $neo->sendCypherQuery($q)->getResult(); </span></span><span> </span><span> <span>$users = $result->get('user'); </span></span><span> </span><span> <span>return $application['twig']->render('index.html.twig', array( </span></span><span> <span>'users' => $users </span></span><span> <span>)); </span></span><span> <span>} </span></span><span><span>}</span></span>
Step 2: Create the showUser controller action
{% extends "layout.html.twig" %} {% block content %} <span><span><span><ul</span> class<span>="list-unstyled"</span>></span> </span> {% for user in users %} <span><span><span><li</span>></span>{{ user.property('firstname') }} {{ user.property('lastname') }}<span><span></li</span>></span> </span> {% endfor %} <span><span><span></ul</span>></span> </span>{% endblock %}
The workflow is similar to any other applications, you try to find the user based on the login.
If it does not exist you show a 404 error page, otherwise you pass the user data to the template.
Step 3 : Create the show_user template file
<span>cd spsocial/web </span>php <span>-S localhost:8000 </span><span>open localhost:8000</span>
Step 4 : Refactor the list of users in the homepage to show links to their profile
<span>$app->get('/user/{login}', 'Ikwattro\SocialNetwork\Controller\WebController::showUser') </span> <span>->bind('show_user');</span>
Refresh the homepage and click on any user for showing his profile and the list of followed users
The next step is to provide suggestions to the profile. We need to slightly extend our cypher query in the controller by adding an OPTIONAL MATCH to find suggestions based on the second degree network.
The optional prefix causes a MATCH to return a row even if there were no matches but with the non-resolved parts set to null (much like an outer JOIN). As we potentially get multiple paths for each friend-of-a-friend (fof), we need to distinct the results in order to avoid duplicates in our list (collect is an aggregation operation that collects values into an array):
The updated controller :
<span>public function showUser(Application $application, Request $request, $login) </span> <span>{ </span> <span>$neo = $application['neo']; </span> <span>$q = 'MATCH (user:User) WHERE user.login = {login} </span><span> OPTIONAL MATCH (user)-[:FOLLOWS]->(f) </span><span> RETURN user, collect(f) as followed'; </span> <span>$p = ['login' => $login]; </span> <span>$result = $neo->sendCypherQuery($q, $p)->getResult(); </span> <span>$user = $result->get('user'); </span> <span>$followed = $result->get('followed'); </span> <span>if (null === $user) { </span> <span>$application->abort(404, 'The user $login was not found'); </span> <span>} </span> <span>return $application['twig']->render('show_user.html.twig', array( </span> <span>'user' => $user, </span> <span>'followed' => $followed </span> <span>)); </span> <span>}</span>
The updated template :
{% extends "layout.html.twig" %} {% block content %} <span><span><span><h1</span>></span>User informations<span><span></h1</span>></span> </span> <span><span><span><h2</span>></span>{{ user.property('firstname') }} {{ user.property('lastname') }}<span><span></h2</span>></span> </span> <span><span><span><h3</span>></span>{{ user.property('login') }}<span><span></h3</span>></span> </span> <span><span><span><hr</span>/></span> </span> <span><span><span><div</span> class<span>="row"</span>></span> </span> <span><span><span><div</span> class<span>="col-sm-6"</span>></span> </span> <span><span><span><h4</span>></span>User <span><span><span</span> class<span>="label label-info"</span>></span>{{ user.property('login') }}<span><span></span</span>></span> follows :<span><span></h4</span>></span> </span> <span><span><span><ul</span> class<span>="list-unstyled"</span>></span> </span> {% for follow in followed %} <span><span><span><li</span>></span>{{ follow.property('login') }} ( {{ follow.property('firstname') }} {{ follow.property('lastname') }} )<span><span></li</span>></span> </span> {% endfor %} <span><span><span></ul</span>></span> </span> <span><span><span></div</span>></span> </span> <span><span><span></div</span>></span> </span> {% endblock %}
You can immediately explore the suggestions in your application :
In order to connect to a suggested user, we’ll add a post form link to each suggested user containing both users as hidden fields. We’ll also create the corresponding route and controller action.
Creating the route :
{% for user in users %} <span><span><span><li</span>></span> </span> <span><span><span><a</span> href<span>="{{ path('show_user', { login: user.property('login') }) }}"</span>></span> </span> {{ user.property('firstname') }} {{ user.property('lastname') }} <span><span><span></a</span>></span> </span> <span><span><span></li</span>></span> </span>{% endfor %}
The controller action :
<span>{ </span> <span>"require": { </span> <span>"silex/silex": "~1.1", </span> <span>"twig/twig": ">=1.8,<2.0-dev", </span> <span>"symfony/twig-bridge": "~2.3", </span> <span>"neoxygen/neoclient": "~2.1" </span> <span>}, </span> <span>"autoload": { </span> <span>"psr-4": { </span> <span>"Ikwattro\SocialNetwork\": "src" </span> <span>} </span> <span>} </span><span>}</span>
Nothing unusual here, we MATCH for the start user node and the target user node and then we MERGE the corresponding FOLLOWS relationship. We use MERGE on the relationship to avoid duplicate entries.
The template:
<span><span><?php </span></span><span> </span><span><span>require_once __DIR__.'/../vendor/autoload.php'; </span></span><span> </span><span><span>use Neoxygen<span>\NeoClient\ClientBuilder</span>; </span></span><span> </span><span><span>$app = new Silex<span>\Application</span>(); </span></span><span> </span><span><span>$app['neo'] = $app->share(function(){ </span></span><span> <span>$client = ClientBuilder<span>::</span>create() </span></span><span> <span>->addDefaultLocalConnection() </span></span><span> <span>->setAutoFormatResponse(true) </span></span><span> <span>->build(); </span></span><span> </span><span> <span>return $client; </span></span><span><span>}); </span></span><span> </span><span><span>$app->register(new Silex<span>\Provider\TwigServiceProvider</span>(), array( </span></span><span> <span>'twig.path' => __DIR__.'/../src/views', </span></span><span><span>)); </span></span><span><span>$app->register(new Silex<span>\Provider\MonologServiceProvider</span>(), array( </span></span><span> <span>'monolog.logfile' => __DIR__.'/../logs/social.log' </span></span><span><span>)); </span></span><span><span>$app->register(new Silex<span>\Provider\UrlGeneratorServiceProvider</span>()); </span></span><span> </span><span><span>$app->get('/', 'Ikwattro\SocialNetwork\Controller\WebController::home') </span></span><span> <span>->bind('home'); </span></span><span> </span><span><span>$app->run();</span></span>
You can now click on the FOLLOW button of the suggested user you want to follow :
Removing relationships :
The workflow for removing relationships is pretty much the same as for adding new relationships, create a route, a controller action and adapt the layout :
The route :
<span><!DOCTYPE html> </span><span><html lang="en"> </span><span><head> </span> <span><meta charset="utf-8"> </span> <span><meta http-equiv="X-UA-Compatible" content="IE=edge"> </span> <span><meta name="viewport" content="width=device-width, initial-scale=1"> </span> <span><meta name="description" content=""> </span> <span><meta name="author" content=""> </span> <span><title>My first Neo4j application</title> </span> <span><!-- Bootstrap core CSS --> </span> <span><link href="{{ app.request.basepath }}/assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> </span> <span><!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> </span> <span><!--[if lt IE 9]> </span> <span><script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> </span> <span><script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> </span> <span><![endif]--> </span> <span><style> </span> body <span>{ padding-top: 70px; } </span> <span></style> </span><span></head> </span><span><body> </span> <span><div class="navbar navbar-inverse navbar-fixed-top" role="navigation"> </span> <span><div class="container"> </span> <span><div class="navbar-header"> </span> <span><button type="button" id="collbut" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse"> </span> <span><span class="sr-only">Toggle navigation</span> </span> <span><span class="icon-bar"></span> </span> <span><span class="icon-bar"></span> </span> <span><span class="icon-bar"></span> </span> <span></button> </span> <span><a class="navbar-brand" href="#">My first Neo4j application</a> </span> <span></div> </span> <span></div> </span><span></div> </span> <span><div class="container-fluid"> </span> <span>{% block content %} </span> <span>{% endblock content %} </span> <span></div> </span><span></body> </span><span></html></span>
The controller action :
<span><span><?php </span></span><span> </span><span><span>namespace Ikwattro<span>\SocialNetwork\Controller</span>; </span></span><span> </span><span><span>use Silex<span>\Application</span>; </span></span><span><span>use Symfony<span>\Component\HttpFoundation\Request</span>; </span></span><span> </span><span><span>class WebController </span></span><span><span>{ </span></span><span> </span><span> <span>public function home(Application $application, Request $request) </span></span><span> <span>{ </span></span><span> <span>$neo = $application['neo']; </span></span><span> <span>$q = 'MATCH (user:User) RETURN user'; </span></span><span> <span>$result = $neo->sendCypherQuery($q)->getResult(); </span></span><span> </span><span> <span>$users = $result->get('user'); </span></span><span> </span><span> <span>return $application['twig']->render('index.html.twig', array( </span></span><span> <span>'users' => $users </span></span><span> <span>)); </span></span><span> <span>} </span></span><span><span>}</span></span>
You can see here that I used MATCH to find the relationship between the two users,
and I added an identifier follows to the relationship to be able to DELETE it.
The template :
{% extends "layout.html.twig" %} {% block content %} <span><span><span><ul</span> class<span>="list-unstyled"</span>></span> </span> {% for user in users %} <span><span><span><li</span>></span>{{ user.property('firstname') }} {{ user.property('lastname') }}<span><span></li</span>></span> </span> {% endfor %} <span><span><span></ul</span>></span> </span>{% endblock %}
You can now click the Remove relationship button under each followed user :
Graph databases are the perfect fit for relational data, and using it with PHP and NeoClient is easy.
Cypher is a convenient query language you will quickly love, because it makes possible to query your graph in a natural way.
There is so much benefit from using Graph Databases for real world data,
I invite you to discover more by reading the manual http://neo4j.com/docs/stable/ ,
having a look at use cases and examples supplied by Neo4j users and following @Neo4j on Twitter.
Neo4j is a highly scalable, native graph database that is designed to leverage data relationships. It is important in PHP applications because it allows developers to store, manage, and query data with its graph data model. With Neo4j, you can handle and analyze high volumes of data in real-time, making it ideal for building social network features in PHP applications.
To install Neo4j, you need to download the latest version from the official website and follow the installation instructions. Once installed, you can configure it by editing the configuration file, usually located in the ‘conf’ directory of your Neo4j installation. You can then connect it to your PHP application using a Neo4j PHP client.
PHP 7.4 introduced typed properties, arrow functions, and preloading, among other features. PHP 8.1 brought enums, fibers, and read-only properties. PHP 8.3, although not yet released, is expected to introduce new features that will further enhance your application. These features can improve the performance, readability, and maintainability of your PHP application.
Adding social network features to your PHP application using Neo4j involves creating a graph database, defining the relationships between the nodes, and querying the database. You can use Cypher, Neo4j’s query language, to interact with the graph database from your PHP application.
Neo4j, as a graph database, is inherently more suitable for social network features than other types of databases. It allows for efficient querying and handling of complex relationships, which are common in social networks. It also provides high performance, scalability, and flexibility.
Migrating your PHP application to a newer version involves updating your PHP installation, updating your code to remove deprecated features and use new ones, and testing your application to ensure it works correctly. It’s recommended to do this in a development environment first before applying the changes to the production environment.
Some common challenges include handling large volumes of data, managing complex relationships, and ensuring real-time performance. These can be overcome by using a suitable database like Neo4j, optimizing your queries, and using efficient data structures and algorithms.
You can optimize the performance of your PHP application with Neo4j by using efficient queries, indexing your data, and using Neo4j’s in-built performance tuning features. You can also use PHP’s performance-enhancing features, such as JIT compilation and preloading.
You can secure your PHP application with Neo4j by using secure connections, implementing authentication and authorization, and using Neo4j’s in-built security features. You should also follow best practices for PHP security, such as validating input, using prepared statements, and keeping your PHP installation up-to-date.
You can find resources on the official Neo4j and PHP websites, including documentation, tutorials, and community forums. There are also many online courses, books, and blogs that cover this topic in depth.
The above is the detailed content of Adding Social Network Features to a PHP App with Neo4j. For more information, please follow other related articles on the PHP Chinese website!