Syncing my knockoutjs models with my backend (PHP) - php

Has anyone implemented something similar?
The problem I have is the fact that we're not using REST. The current plan is the following:
Create a controller called sync($modelName, $action) and throw all requests at that.
Create an interface called "syncable" and force models to implement it.
How it works:
GET http://localhost/sync?modelName=User&action=update&first_name=Peeter
This will look for a model named UserModel that implements the syncable interface. If found, update its parameters and update(); to db.
The syncable interface is to enable per-record actions. E.g. "Only record owner can update this record" or "Only admin can delete this record".

I wrote a fully function REST API framework into symfony 1.4. It supports JSON and JSONP. I've open sourced it, so you're welcome to use it. We're using it in production with a lot of traffic, so it's pretty stable and we've had great feedback from the consumers. It's really flexible and very fast to write API methods. We also have a documentation page that allows you to make test queries. It's one of the best API docs I've seen.
https://github.com/homer6/blank_altumo
See this (below) for an example of an API controller. This contoller only shows GET, but PUT, POST and DELETE are fully implemented.
https://github.com/homer6/blank_altumo/blob/master/htdocs/project/apps/api/modules/system_event/actions/actions.class.php
If you need help getting it going, I'm willing to spend a few minutes to explain its design or get it working for you.
Hope that helps...

I had the same issue with an app I'm working on, so I implemented a ChangeTracker that subscribes to my observable properties, and tracks any changes made. Then, at any later point, I can call something like:
viewModel.changeTracker.commit();
which is responsible for massaging my change objects into a format that the server understands, and ships it off for processing.
Here is a little fiddle demonstrating the idea. http://jsfiddle.net/ggoforth/pCX8c/2/
Note: I've had a string of days where I've been working till 3am so there may be a better way of doing this, and I'm just to exhausted to realize it :)

Related

Seeding Laravel DB from external API

I'm new to Laravel. Maybe my questions are a little bit silly... Sorry...
The goal: There are some API resources and I need to take some selective data from them (It will be needed to make extra API queries from data which I already got before to get full sets of required values) and fill my DB tables with it (some as one to many, some as many to many).
The problem: What Laravel tools do I need to use to reach this goal? Is it factory, seeder or somewhat else? In addition I don't understand where I have to write the code for getting data from an external API and where (in terminal manually?) I have to initiate my DB tables filling.
Maybe someone could at least advise what to learn in the Laravel official documentation at first or some helpful reference to some article from which I will be clear how this process may be implemented in Laravel. I mean the tools' set and order to use them. Not the finished code implementation of course.
I will be grateful for any help. Thanks. Sorry for my non native English.
Well, there are multiple ways of achieving what you want:
One is to create a command where you are going to write code to fetch this data (using curl or any similar way). And then you manually run the command when you want with whatever arguments you want.
Other one is to use the previous step and schedule it to run in a desired time with desired arguments.
Other possible way is, if the external API can send data to a specific URL when some action occurs in that system, then you can create a normal Route and the API should point to this Route in your Laravel. It will be specific and only work for this API.
Other one is to fetch data based on an event. Let's say that, if a user register, when this is successful, you are going to fetch User info from an external API using their email (let's say you want to get a profile picture from an API and the only way to get the user picture is sending the user's email). You can do so using Events.
There are more ways, but if you don't give too much context, then this is what I can share with you !

What is the best practice for using services in Symfony instead of Controllers and not only there?

Well i'm learning Symfony (3.3) and i'm little confused about Service Container. In first tutorial the lector show register, login, add post, edit, delete methods in User, Article Controllers. Then in other tutorial, they show same methods but use Service Container (User and Article services) with User and Article interfaces. So .. what is the best practice for implementation in Services instead of Controllers.
I would like to add to Alexandre's answer that it is considered best practice to keep your controller 'thin'. In other words, only put code in your controller that really has to be there (or if it only makes sense to put it in your controller).
Services are like tools you can use in your application. A service in an object that helps you do something. In one service, you can have many functions. I think the best way to understand the difference is that a controller is for one specific action, a service can be used in many actions. So if you have parts of code that you want to use in more than one controller, create a service for it. And for the sake of re-usability, create functions in your service that do only one thing. This makes it easier along the way to use these functions.
the "best practise" depends on what you want to do with the Service. If you build an REST-Api you might want to do Database-Operations in Controller. Why? When you rely on the SOLID-Pattern you want to reduce or eliminate redundant code. If you code a real REST Api you don't have redundant code because each REST-Verb will do a different query/thing.
So in a non-REST-Api-application you will have a lot of redundant code. You do the same things/services on different pages/controller-actions. So the best thing is to implement all the business-logic in services to have it only one time in one place. If you have a lot of individual queries place them into repositories. If you have business-logic that fit's into an entity-class place them there. So in my opinion you can choose a thick controller/no service design in API's and a thin controller/thick service design in classic symfony front-/backend applications.
But one more thing: there is no totally wrong way to design an application. But if you work with other people or want to run the application longer than a month (without having trouble to maintain it) you should pick a common design-pattern.
Controller must implement the application logic like check if it's a post request or if a form is submit etc...
Never use DQL or any SQL Request directly inside a controller !
EDIT In the example i use a find method inside the controller because it's a Repository method but i parse the result inside slugify (my service method)
Services contains business logic like formatting phone numbers, parse some data etc...
Of course you can inject a repository inside a service and call your methods inside it.
An example:
//This is a fictive example
public function indexAction(Request $request) {
//Application logic
if(!$request->get('id')) {
//redirect somewhere by example
}
$article = $this->getDoctrine()
->getRepository(Article::class)
->find($request->get('id'));
//Business Logic
$slug = $this->get('my.acme.service')->slugify($article->getTitle());
}
Hope this helps

MVC + REST + nested resources + single page app

I'm a novice, but struggling hard to implement this interactive application I'm working on "the right way" or at least a good way in terms of scalability, maintainability, modularity, development speed and tool independence. That's why I chose the REST design guides and a framework which implements MVC.
However I can't get my head around where to put what in the following situation and any input or reading material from a more experienced developer in this techniques would be greatly appreciated :
I'm developing a single page web app which creates a resource that has several nested resources within. In the create methods and alike, I need to call the create methods from the nested resources. Right now every GET request is responded with a JSON, which the front end then parses, shows and add dynamically to the page accordingly. The question is : where should this create and store methods from nested resources be, in the controller or in the model?
Currently, my approach is : since the controller function is to handle user input, interact with model and return the view accordingly, the nested store methods are in the model since they're not created independently, their create methods are in the controller since they're requested from ajax calls, but this isn't nested, and so on. I'm worried that this is too mixed up and not general.
Am I ok ? Am I mixed up? I don't wanna make a mess for my coworkers to understand. Theory becomes tricky when applied..
I'm gonna have a go at this. I am myself still learning about this as well, so if any information is wrong, please correct me.
In terms of scalability, you should always be able to create any model independently, even though at this point it appears not strictly necessary. The REST paradigm stands for exactly this: Each model (a.k.a. resource) has its own (sub)set of CRUD endpoints, which a client application can use to perform any action, on any composition of data (compositions in which elementary entities are mostly the models you specify).
Furthermore, a model should be concerned with its own data only, and that data is typically found in a single table (in the case of relational datastores). In many cases models specify facilities to read related resources, so that this data can be included when requested. That might look like the line below, and the response is ideally fully compliant with the JSON API specification:
GET //api/my-resources/1?include=related-resource
However, a model should never create (POST), update (PUT) or delete (DELETE) these relations, not at all without explicit instructions to do so.
If you have a procedure where a model and its nested models (I assume related models) are to be created in a single go, an extra endpoint can be created for this action. You'd have to come up with a sensible name for that set of resources, and use that throughout your application's HTTP/support layer.For instance, for creation of such a set, the request might be:
POST //api/sensible-name { your: 'data' }
Keep the { your: 'data' }
part as close to a typical JSON API format as possible, preferably fully compliant. Then, in your back-end (I suppose Laravel, inn your case) you'd want to create a factory implementation that might be called <SensibleName>Factory that takes care of figuring out how to map the posted data to different models, and how their relations should be specified. Under the hood, this factory just uses the model classes' creation facilities to get you where you want to go.
When you would instead automate this process in your model it would be impossible to create the resources independently.
When you would instead automate this process in any single-resource controller that would be non-compliant with the REST paradigm.
With the factory pattern, you explicitly use that class to perform the higher level action, and none of the above concerns apply, not speaking about whether this approach is in accordance with REST at all.
The key takeaway is that the exact same result must still be achievable by performing multiple requests to single-resource endpoints, and your additional /api/sensible-name endpoint just substitutes for the need to call to those multiple endpoints, for the purpose of convenience, when you DO want to create multiple records in a single go.
Note that my statement has little to do with what endpoints to create to fetch nested resources. This SO question has some pretty good conversation as to what is acceptable, and how your specific needs might relate to that.
In the end, it's all about what works for you and your application, and REST and the like are just philosophies that propose to you an approach for similar needs in general web development as well as possible.

Properly making requests to a 3rd party API with Laravel 5.3

There are several questions on here that are similar, but not that are really providing exactly what I need.
I am creating a simple pet project in Laravel 5.3 that uses https://xboxapi.com/ to pull in JSON of Xbox Games. At first I was going to create a Game model, but I understand that because I am using 3rd party, I really won't be pulling any data in from my own DB and there's really no need to use Eloquent ORM at this time.
What is the "Laravel way" to do this? I can use Guzzle to hit the API, and create methods to get game by title, get game by publisher, etc. I guess what I am asking is where does this go within my app's file structure? I understand there may be no right or wrong answer. Really just looking for some insight into improving my OOP concepts.
Edit
Should I just put this into a GamesController? I don't want to have Guzzle in my controller, right?
Or should I actually create a Game class that extends the Eloquent model, and then overwrite methods like ::all() and ::find() to hit the API rather than the applications database?
Thanks ahead of time!
Yes. Use Guzzle. The PSR-7 spec has implemented 3 RFC's that dictate how HTTP request objects should be handled.
Guzzle does have PSR-7 support, you can see the git repository here.
For API based CRUD requests, create a new Controller namespace and move your API logic there. Consume your own API's internally if you need through these external end points:
artisan make:controller Api\\UserController
Now update your RouteServiceProvider, and add a new declaration:
private $api_namespace = 'App\Http\Controllers\Api`.
Now update your mapApiRoutes() and change your namespace:
'namespace' => $this->api_namespace
Now all of your API requests should route to Api\Controllers.

How to add my own oauth provider for phabricator?

I want to add my own oauth provider. After reading this, I added a PhabricatorFoobarAuthProvider.php in phabricator/src/applications/auth/provider/ and added a PhutilFoobarAuthAdapter.php in libphutil/src/auth/ and then executed arc liberate seprately. I expected to see Foobar provider to show in this page: localhost/auth/config/new but I didn't. What need I do to reach the goal? Am I forgetting some steps? Thanks.
I use `install_ubuntu.sh` to install phabricator. The layout is like this:
phab
....install_ubunut.sh
....arcanist/
....libphutil/
....phabricator/
So the english is a tiny bit broken but i'll answer this the best that I can. What I assume you are trying to do is figure out is "how can I add my own Oauth provider?". In doing so you came across this magical function that seems to be doing something but your not sure what.
The PhutilClassMapQuery is essential to understanding phabricator and arcanist. If you grep -R "PhutilClassMapQuery" . you will find around 100 different places that it is used. Every place that this is used you as the user are able to load in your own classes that integrate seamlessly with the Phabricator application.
I'll use PhabricatorAuthProvider as an example. If you look here you will notice that this is an abstract class. What the that function does is say load in every class that extends the current class of PhabricatorAuthProvider. So as an example if you look here you can see that this class provides Persona authentication and it does that simply by implementing the needed functions.
I am not going to go through the rest of this but you should be able to figure out the rest based on the above and using this link which shows you how to load your classes into Phabricator.
Hope you enjoy. Phabricator is some of the nicest PHP code that you will find.

Categories