PHP is only as bad as the developer. Modern PHP is a perfectly usable language, and, as you mentioned, will run on just about any hosting service.
A lot of the criticism isn't necessarily of PHP as a language, but its users. Since PHP is so popular, it naturally attracts inexperienced developers who tend to neglect best practices in exchange for simple, fast deployment.
My advice is to try and follow best practices with PHP. I recommend checking PHP: The Right Way.
It may also be worth checking out a framework like Laravel (+ Laracasts), which covers a lot of bases for you.
Laravel uses an Active Record style ORM called Eloquent which is very easy to use. It also uses a templating system called Blade which is also great. And lastly, Laravel uses Symfony components where it makes sense. My vote is for Laravel.
References: http://laravel.com/docs/eloquent http://laravel.com/docs/templates
EDIT: After reading the comments I thought of another cool Laravel plus. It has the "Artisan" command console which let's you write a lot of infrastructure code without actually writing ANY code. In addition, Jeffery Way created some great generators that can be added in to really take it up a notch. If you are a sublime text user, there is a generators plugin to make it even easier. And finally, Laravel has migrations which is a godsend over many of the other frameworks I have used.
PHP gets a lot of hate but it's faster performance wise than Ruby on Rails or Python with Django and is far more widely supported on web servers than either of those languages. It's easier overall to setup and configure than ASP.NET and doesn't require $600+ for a license of Windows Server.
PHP lends itself to spaghetti code if someone doesn't know what they are doing since it doesn't force any design paradigm on you. You can still write pretty decent OO code if you decide to make it a priority. If you haven't seen it check out the laravel framework which in many ways feels similar to Rails.
Give your route a name with 'as'.
Then when you want to redirect use
redirect()->route('your_route_name');
Edit: Docs for the named routes: http://laravel.com/docs/5.1/routing#named-routes
You can create a virtual machine with Vagrant and Laravel Homestead. The nice thing about this is if you screw up your environment, you can just make a new virtual machine.
http://laravel.com/docs/master/releases
You are comparing a framework (Rails) to a language (PHP), of course Rails is going to feel easier to use compared to PHP but it's not at all a reasonable comparison. You want to compare Rails with one of the popular PHP frameworks, the best comparison would probably be Laravel.
PHP has come a long way in the past 5 years, I'd be very careful when reading any articles criticising it that are more than a few years old because they are likely talking about issues that don't exist any more. There are obviously still plenty of flaws with the language but a lot of the big issues have been addressed and generally the language is moving in a good direction with PHP 7 looking very promising. Basically, properly written, modern PHP is nice.
PHP absolutely works for big, long term projects assuming the developers are considering architecture and designing it to be maintainable. Is a big mess of procedural PHP suitable for a long term project? No, absolutely not. While PHP allows you to write your code as a big procedural mess and have it run that's (mostly) the fault of the developer not the language.
Really though, I wouldn't look at whatever language you choose as this real long-term commitment. You're going to be learning programming skills that will apply to any language, and specifically you're going to be learning about MVC architecture which will translate to any project where you uses that pattern. If you're an experienced Ruby/PHP developer, learning the other language isn't going to be starting from scratch.
A thousand times, Laravel. It is hands down the best PHP framework I have ever used.
You can knock together a CRUD app with it in no time; the form helper methods are really good, and do some clever stuff if you give them a data model to play with, and I have to say that their ORM is the best I have used, even better than Rails.
I wouldn't immediately discount Laravel for that. It's a fantastic framework and the fact that you have the option to use facades or not is great for people on all levels. My wish is that Laravel's docs equally emphasized injecting the dependencies rather than the use of facades.
Also, shame on me for not looking at the docs recently. The Facade Class Reference would have been a big help before writing the article. Not sure when that got added.
> Want to know how to stop using Facades? Google
Uh, No?
Those two sections are the only thing you need to read in order to know how to stop using facades.
Want to inject the instance that lies behind the Cache facade?
From step 1 we know it's Illuminate\Cache\Repository
From step 2 we know we can just do this:
<?php
use Illuminate\Cache\Repository as CacheRepository;
class Whatever { protected $cache;
public function __construct(CacheRepository $cache) { $this->cache = $cache; } }
Done.
You don't need Google, you just need to actually read the docs, and reading Laravel's docs is like an easy stroll along the beach on a warm summer day.
The general term is routing. All PHP frameworks offer it in some form. There are some standalone libraries available too, apparently.
http://stackoverflow.com/questions/15392024/is-there-an-standalone-php-routing-library
> <p class="attribution wow fadeIn animated" data-wow-duration="0.8s" data-wow-delay="2.2s" style="visibility: visible; animation-duration: 0.8s; animation-delay: 2.2s; animation-name: fadeIn;">Inspired By <3 <a href="http://laravel.com" target="_blank">Laravel</a></p>
Wow I thought having a webpage with unnecessary animations was like soooo jQuery-2009-late...
Gross!
Laravel comes with a handy Log
class that you can call from anywhere:
\Log::info('Interesting information about my app'); \Log::warning('Potentially dangerous thing happened');
There are actually 8 log levels defined: http://laravel.com/docs/master/errors#logging
You can also pass an optional array of contextual data:
\Log::debug('The user logged in', ['user' => $user]);
You can use tail -F
to watch the log file as your application executes.
If you want to be able to step through your code and manipulate variables during runtime, I highly recommend checking out xdebug.
It seems like a lot of features aren't outright depreciated, but are hidden from documentation to discourage people from using them. Like with what happened with HTML / form builders, which disappeared from the documentation ~4.2. You have to do some serious digging to rediscover their existence.
In my opinion, it seems like Facades are dropping out of favor due to the framework leveraging namespaces a lot more. But I haven't seen anything official either way.
I wish they would either explicitly depreciate something or keep supporting it in documentation. Passive-aggressively removing something from documentation without any notice of deprecation and generating ambiguity of support around a feature is pretty annoying.
So, I think the problem here is related to eager loading vs. lazy loading.
Lazy loading is when you don't define a "with" clause and just load the relationship dynamically, if you're looping through these then every time you query the relationship you're going to be executing another query on the database. Eager loading is when you use a "with" clause, and it produces that big query you see at the end of your query screenshot. It does two queries total, it selects the records from the main table and then a second query to select any related records from the related table and then assigns them to the correct main table records in PHP. This is much, much faster than using lazy loading when it's being called more than once or twice.
I'd suggest reading through that doc and applying eager loading to all your queries.
Check out view composers. Something like
View::composers(array( 'UserComposer' => 'layouts.master', ));
class UserComposer {
public function compose($view) { $user = null; $user_id = Auth::id(); if (!empty($user_id)) { $user = User::find($user_id); } $view->with('user', $user); // logic for points..etc } }
Ah, here it is. You're outside basic Laravel convention here and you're going to end up fighting the framework. You need to be referencing Laravel routes defined in your routes.php, not specific files, from your jQuery.
So your $.post should be to something like '/users/find' or however you want to define it in your routes.php.
The best fit for a Go component in a PHP app would be doing asynchronous work via a Message Queue like beanstalkd.
Push messages to queue from PHP then consume them through Go and do the specified work.
I personally like Laravel's approach to queueing jobs in PHP, but you can definitely roll your own using the various beanstalkd wrappers for both languages.
The disadvantage here is that PHP wouldn't be able to directly access the results of a Go operation, you'd have to check an intermediate data store for results (I personally like Redis for this), but I've always thought Go would be a great fit for computationally intense, asynchronous tasks on a web server.
So your problem doesn't seem to have anything to do with php, apache, or mysql. SMTP is an email protocol and in context of your error it means that you need to have an email server setup or configured for this application to work correctly. As far as the other requirements are concerned, it says on the GitHub page that the tutorial covers how to install/fulfill them.
Honestly though, if you're going to build an application of some sort, I'd suggest a more fully-featured framework. This one looks interesting, but isn't really intended to be a full framework, just the login portion. It may seem like more work to start with, but learning a framework gives you some big advantages, one of which is having an entire working site in a very short time. I'd suggest you have a look at something like Laravel to get started with.
Also, to use Laravel, you don't need to setup or have an email server.
wow, ovo je laravel framework... i ovo je Laravelova stranica koja je'lte prikazuje detalje errora. Pisano pravilo (dakle skoro pa 101) u svakoj web aplikaciji je da se u produckiji iskljuci debugging (a zbog sigurnosti) .
http://laravel.com/docs/errors
>By default, error detail is enabled for your application. This means that when an error occurs you will be shown an error page with a detailed stack trace and error message. You may turn off error details by setting the debug option in your app/config/app.php file to false.
>Note: It is strongly recommended that you turn off error detail in a production environment.
Laravel popped up recently, and while I haven't tried it, the docs are very solid and it looks to be pretty well written. While it's not quite micro (Footprint of half a meg vs Sinatra at something like 150k), it isn't absolutely huge either and it might be worth a look.
Thanks for the feedback. I spent a lot of time on the documentation because I knew it could make or break everything I had done. As far as Sinatra and Rails, I consult their implementations for most features. Learn from the best!
Also, for what its worth, there is a class API here: http://laravel.com/api
Laravel is an amazing PHP framework that has done wonders for modernizing the language and, in my opinion, has one of the better development communities out there. Not sure what you mean by not being in any of the newer frameworks...do you mean stacks?
Edit: Forgot to mention, if you only hear about PHP in the context of wordpress you're not looking in the right places ;)
I didn't use Laravel much before Laravel 5 so I can only tell you what they mean currently.
A console command is an Artisan command that you would trigger from the command line, be that directly by typing php artisan {your command}, through a CRON job or using Laravel's task scheduler. A console command class is similar to what a Controller is when you are using HTTP. This is the answer to your question at the end of your post.
Laravel's task scheduler is a feature that brings your CRON setup into your code and therefore into version control. You have to set up a CRON job that runs the scheduler every minute and it will then trigger certain tasks based on how you have configured it. It's a pretty neat feature that's a lot clearer and easier to use than just making individual CRON jobs.
A job is an object that is designed to be put onto a queue. When you dispatch a job, the object gets serialized and put into your database/redis/whatever and then your queue listener will unserialize it and execute it's handle() method. You would use this when a user's action needs to trigger some sort of functionality that might take quite a long time to process (e.g. sending some emails). You can add this functionality without making the user wait around for it to be completed.
A command was the name used when referring to Jobs in Laravel 5.0 (they were renamed to Jobs in 5.1). The name is because it is based on Command Bus architecture. You shouldn't see anything new referring to Commands in 5.1+, if you see it anywhere it is just for backwards compatibility purposes.
Define API. Do you want to create a REST API that provides CRUD capabilities on your application?
If that's the case, the most straightforward approach is to write additional routes and controllers to provide the API endpoints you need. Some advice pertaining to that:
Wrap your route definitions in a group so you can prefix both the URL and the controller namespace. Example:
// API Route::group(['prefix' => 'api', 'namespace' => 'API'], function() { Route::resource('team', 'TeamController'); });
Use existing authentication along with HTTP basic auth as a simple auth mechanism for your API (see example middleware in one of my projects: https://github.com/Riari/laravel-forum/blob/l5-refactor/src/Http/Middleware/BasicAuth.php)
For the most part, you can write your controller methods just like you normally would, only without returning views or redirect responses. A REST API should only ever return a formatted response with an appropriate HTTP status code - JSON being the most popular format to use. In fact, returning a model or collection directly from a controller will result in it being automatically cast to JSON, so that makes life easier for you if you want to take that shortcut.
Beyond that, you'll need to be a lot more specific about what you want to do :) but hopefully this helps you a little.
Take a look at View Composers. You can bind your data with the composer making it available in all the views, and you can specify which views/controller views to make it available for.
Good luck!
I'd really suggest reading the Laravel documentation before asking a question here, particularly the Eloquent section. Nobody is going to be able to provide an answer more succinctly than just reading the docs.
To briefly cover it, you presumably have two tables, right?
Possibly something like this:
users
id
username
posts
id
title
body
user_id
If you set up a relationship in the User model like this:
public function posts() { return $this->hasMany(Post::class); }
Then you can just grab any posts belonging to your authenticated user with:
Auth::user()->posts
If this is all still confusing to you, I'd recommend the Laravel 5 Fundamentals series.
You need to use whereHas()
for relations, not where()
.
http://laravel.com/docs/5.0/eloquent#querying-relations
For example, your query would become:
Task::whereHas('users', function($q) use ($userId) { $q->where('id', $userId); // this 'where' is attached to the users relation scope
})->where('project_id', $id)->get(); // this 'where' is attached to the task scope
Alternatively, if you your task table has a user_id
column, then you could just do this:
Task::where(['project_id' => $id, 'user_id' => $userId])->get();
But that will only work if you do in fact have a 'user_id' column in your tasks table. If you have a many to many relationship with tasks and users, then you'll need to do what I recommended above.
It maps a request to a method. A GET request to /auth/something would look on the AuthController for a method called getSomething(), if a POST is made to /auth/something then it'll look for a method called postSomething(). So /auth/register as a POST request would find . IMO it's a terrible way of doing things, because you don't know what methods actually exist, without having to dig into the controller.
I know you said you don't want docs, but the docs do explain this - http://laravel.com/docs/5.0/controllers#implicit-controllers
Maybe you can take a look at Laracast they call it the netflix for developers...
I found this video for you https://laracasts.com/series/laravel-5-fundamentals/episodes/15 And you can take a look at: http://laravel.com/docs/5.0/authentication
Good luck with it.
Authentication is quite extensively covered in the L5 docs.
As for your implementation, you could just edit the users table / migration to include the is_super, is_admin, is_contractor and is_client booleans. After doing so, you can access the autheticated user's properties like Auth::user()->is_admin etc.
Or.. you could look into user roles and use a package like ENTRUST.
You should check out /r/phphelp. It's more suitable for your question. There are some good links on the side bar of that subreddit. PHP The Right Way is a good place to start. If you're looking for a framework like Rails, Laravel is your best bet.
You forgot the most important part, why are you turning it into an array in the first place? Why aren't you sorting the collection or the query?
Have you gone through the collections documentation? http://laravel.com/docs/4.2/eloquent#collections
One of my favorite, and somewhat underutilized features of Laravel are its View Composers. Assuming you are using 'languages' and 'categories' for dropdown lists, or the like, you can use a view composer to attach any required data for you.
For example: create a view file called languages.blade.php. In it include the code for a dropdown list, much like you would have in 'books.create'. Then you bind a view composer to the languages.blade.php view file like so:
View::composer('languages', function($view) { $view->with('languages', Language::lists('language', 'id');); });
This means anytime you include the languages.blade.php partial view, the languages data will be automatically bound. So in your original 'books.create' view, add '@include('languages')' and you will have your dropdown list with your bound data inside it.
Jeffrey Way over at Laracasts has an excellent video on using View Composers if you want to learn more.
The docs just show you what Laravel can do but not enough about the recommended way to use it. They're very good and I use them all the time for reference.
For example, the piece on model events, a very useful feature that works well. The docs give you 2 or 3 ways to use them but doesn't tell you under which circumstances you'd use which or in which file the should go. I love that Laravel doesn't force you to do thing a specific way but that much choice makes it hard on newbies.
For learning Laravel you need more depth, I would recommend Daylee Rees' book Code Bright.
Expanding on the protection of sensative data there is now actually a built in way to do that. It is explained in the config docs. Makes it pretty easy overall.
Laravel is a great framework for developing web apps. You will want to start by reading the documentation. Then, go through some Laravel tutorials.
Honestly CI is great and I've used it tons of times for tons of projects, but it'd be better to start out with something more modern, CI still have alot of bad ways of doing things, that where good back in the day but make no sense now. So it's really not the best place to 'learn'.
I'd strongly recommend going with laravel it's very similar but utilises modern concepts and features.
Seriously I love Codeigniter, but if you get on that bandwagon now you'll either have to jump off very soon or be left behind, i've found it so dificult to move on from CI even though I know there are better things out there, simply because I know CI well.
So seriously put yourself on firmer ground to start off with and go with laravel.
I use Laravel as a backend API with Angular or other JS on the front, also.
I do the same things as /u/mbdjd but instead of over ridding the getter I convert my data to a view model before sending it to the front end. I do the timestamp conversion there.
Or...you can use accessor to do the conversion just for the date fields on the model.
Earlier on the Laravel site, I spotted these which may be of some use to you.
I'm assuming you are using auth attempt
http://laravel.com/docs/5.1/authentication
From where it talks about the attempt method:
"If the user is found, the hashed password stored in the database will be compared with the hashed password value passed to the method via the array. If the two hashed passwords match an authenticated session will be started for the user."
I see in your image that the passwords are plain text. So even if you pass the correct password in with the form the attempt method is calling bcrypt on your password sent in from the form. Once it is hashed it is not going to match the plan text password anymore.
I supposed you could go through the source and see how to keep it from bcrypting (if it will even let you), but the smarter and much safer thing to do is bcrypt your passwords before saving or updating them.
Hopefully that fixes your issue.
Edit: Going a bit further, instead of trying to remember to hash your passwords on save/update/db seeding just add an attribute mutator to the User class e.g.
public function setPasswordAttribute($password) { $this->attributes['password'] = bcrypt($password); }
Access the pivot
property on the relation to get the other fields, something like $character->pets->first()->pivot->level
. First though you need to add ->withPivot('level', 'other_field')
to your relationship. See http://laravel.com/docs/master/eloquent-relationships#many-to-many.
I don't know about the best practice, but if you have your Eloquent relationships set up you can use the sync() method where you pass in an array of hobby IDs that are in the final set. It will delete existing records that aren't in that final set and create those that aren't in the table yet.
Example from the documentation:
$user->roles()->sync([1, 2, 3]);
If I'm understanding you correctly, I think this is what you're looking for:
Key::with('value')->all();
From the docs
It's a bit strange that this would be removed from the docs, but here's an excerpt from the 5.0 docs:
> Note: The difference between the X-CSRF-TOKEN
and X-XSRF-TOKEN
is that the first uses a plain text value and the latter uses an encrypted value, because cookies in Laravel are always encrypted. If you use the csrf_token()
function to supply the token value, you probably want to use the X-CSRF-TOKEN
header.
For a bit more detail, you can read barryvdh's post on CSRF protection.
Glad you figured it out :) however, for something like that, personally I would be tempted to use resource controllers instead. They may be primarily designed for building REST interfaces, but I find them ideal for building admin panels too since they give you a means of listing (index), creating (create, store), updating (edit, update) and deleting (destroy) while only having to worry about a single parameter for each model.
It's even better if you combine it with model binding!
Here's a quick example:
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function () { resource('news', 'NewsController'); });
Route::model('news', 'NewsArticle');
Then in your controller:
public function edit(NewsArticle $article) { return view('admin.article.edit', compact('article')); }
You can even be clever with your create() method and do this:
public function create() { return $this->edit(new NewsArticle); }
...and in your admin.article.edit view, you can do:
@if ($article->exists) Editing @else Creating @endif article (etc)
Anyway, you get the idea. Sorry if I'm pointing out things you already know about. This is just the approach I've ended up sticking with for the most part :)
If you have access to the bash, register environment variables (e.g. by source
ing a .env file containing SQLPW=asdf
) and use your programming language's features to fetch these variables ($_ENV["SQLPW"]
for PHP or process.env.SQLPW
for Node). Many frameworks ship with this behavior (Laravel, Express, ...). Just don't check in your .env file.
I've been a PHP dev since the late 90s. It took me a while to come around to the Laravel way of doing things (originally I was looking at Symfony and Yii), but I loved it once I understood it. It does so much to make coding easy and fun, and it doesn't have the limitations that some people think it does.
> -uses active record
If you prefer a Data Mapper, you can use Doctrine or others with Laravel which some people do prefer. It doesn't force you to use Eloquent. Personally I vastly prefer the simplicity of using an Active Record (Eloquent) model, but domain programming purists don't like that it breaks some of the rules of that methodology.
> active record which apparently is not testable,
You can unit test Eloquent, but it's a different process than with a Data Mapper.
> and extends Eloquent class, meaning you can't inherit and make higher abstraction level classes
That doesn't make any sense. You always inherit it and make higher abstraction classes when using it. I'm not sure what they mean by that.
> uses global variables that will slow down application
<sigh> That's everyone's first criticism of Laravel and it's based on a misunderstanding. It appears to use static classes, but those are what Laravel calls "facades" and they're actually dynamically resolved, but give you the simplicity of using them as if they were static classes. Facades are entirely optional, and some devs prefer techniques like dependency injection which is also available (more work, but more flexibility).
They real question is if you should store code in the DB like this. You lose version control if it's in the DB, unless you implement it yourself. There are also performance implications as the code execution is likely to be worst than include due to the need for dynamic interpretation of the code string.
There is nothing wrong with your str_replace approach but current PHP methods use frameworks with template engines. Where the code is separate from the presentation layer like the example axvk provided.
Read about phalcon or laravel
For a quick fix use eval as suggested, if you hit a performance wall which I doubt you will you could cache the files to disk from the DB and use include instead.
It gives me bad memories of Ruby On Rails. Active Record was the thing i liked the least about it. If I extend the Model class, then i can't extend anything else. I prefer the Datamapper approach of Doctrine, where my model isn't polluted by the ORM. It makes reasoning about it (and testing it it) a lot easier.
EDIT: i reread the documentation (http://laravel.com/docs/5.0/eloquent) to make sure i had the right conceptualization. Pretty much everything on there is the opposite of how i'd want to do it.
>I'm a little wary of that. It's hard to get folk to work for free in the web industry, particularly work of that caliber (I took a quick look at the site's source code on the Wayback Machine) and especially if it's a for-profit company.
I feel pretty confident it was all done for free. I posted another comment a few mins ago but I briefly volunteered to help with backend stuff. There were dozens of to-dos in the project on freedcamp that were completed or in progress, all related to backend development, and separately there were people chatting as they actively worked on graphic design(logo, images, etc. -- for example, the "addict approved" logo in the OP was one of the things I saw being worked on).
Here's an example of a to-do I still have from an email:
>[her name] assigned a todo: >Create MySQL migration script for laravel >We need a script added to the project that will bring up a fresh schema from scratch if one does not exist. See http://laravel.com/docs/quick#creating-a-migration for details. >Assigned To: [my name]
This was the type of shit she was asking people to do for free. By that time it seemed like the bulk of the backend work had already been done by another guy who as far as I know was also volunteering.
I'd consider virtualization for the following reasons:
1) Your virtualized environment can be almost (if not exactly) identical to your eventual production server
2) You can make snapshots of your VM whenever you want, which backups not just the web site(s) but the entire configuration of the vm.
3) Portable. You've now decoupled your development environment from your host machine. If you need to switch machines, upgrade, downgrade, etc, it's super easy to move that VM to a new machine.
4) If you ever need to work with multiple frameworks or multiple versions of software that have different levels of dependency, you can setup multiple VM's with the exact requirements for that framework or software.
I believe most people use Homestead to setup Laravel 5. I personally don't have any experience with Homestead, as I prefer to setup my own environment myself running on Ubuntu 14.04 Server.
I used to use WAMPServer on Windows 7. Then I got vagrant and homestead and never looked back.
However, it is relatively simple: http://laravel.com/docs/5.0
Please note that using closures in routes is generally a bad idea. It breaks the single responsibility principle. I know that the official routing documentation has lot of closures but they are more for illustrative purposes I guess. 99% of the times you point them to resource controller and their methods.
http://laravel.com/docs/5.0/controllers#restful-resource-controllers
But generally I agree it is a good question why the official routing documentation has examples which are pretty much never used in real life. Now the most common use case in resource controllers, not in routing.
I've been involved with 5+ different Laravel 3/4 projects in the last 2 years, 4 of them employed this pattern. They were all done by different people, and it was something completely new to me and I've used other PHP frameworks and Rails extensively in the last 5 years. (So I'm familiar with both the Active Record and Data Mapper patterns)
I've also seen it recommended often by people who advocate Laravel in blogs, on forums, here on /r/PHP , StackOverflow etc. I've seen multiple blog posts actually calling this the repository pattern etc.
So no, the article didn't mention Laravel, but I'm fairly certain that the author encountered this anti-pattern in Laravel projects.
ALSO: I'm not 100% sure, but I sorta remember the Laravel docs recommending this pattern in the v3 days. Around 2 years ago.
EDIT: I'm half right, the docs were not recommending this exactly http://web.archive.org/web/20120427222355/http://laravel.com/docs/models#best-practices
Do you only have static information about your site? If so, the easiest thing to do is put that information into a configuration file and then access it globally with
Config::get('site.name')
or Config::get('site.contact
) where 'site' refers to a site.php file in your configs folder.
If you have more dynamic data that varies on each request, you'll want to create global Middleware:
https://laracasts.com/series/laravel-5-fundamentals/episodes/16
Or a service provider:
http://laravel.com/docs/5.0/providers
Either way, if you want that information to be available, you need to bind it into the IoC container in your middleware or your service provider.
What is the point of Laravel's Elixir tool? It looks like it’s a wrapper for gulp
. Haven’t we already had this discussion how make
and friends are easier to use than gulp
with less dependencies? Why not show examples on how to do that instead of making build tools for build tools and wrapping wrappers for perfectly easy to use CLI tools?
Not to mention it's treading on Elixir language's name with its own build tool/package manager, <code>mix</code>… this is just going to add more noise for people trying to Google their Elixir issues.
To add extra properties to a model, you just need these two pieces of your code in your model:
protected $appends = array('x');
protected function getXAttribute() { return 'abcd1234'; }
Replace 'x' with the relevant attribute. See: http://laravel.com/docs/eloquent#accessors-and-mutators
I'll check it out but a fairer representation of your first example would be
user = User.find(1) vs $user = User::find(1);
as pointed here, as for the second example im not sure what resources entails inside of rails but theres more efficient ways to do routing in Laravel, you can send a route to a controller which takes care of redundant routes, example
Route::all('/post/{action}/{?id}', 'postController@handle');
> It's definitely bad for large jobs
> it doesn't do a good enough job at separating MVC
PHP has frameworks for that, Laravel comes to mind.
PHP gets such a bad rep! But it's come a long way.
You can find a list of the bindings here: http://laravel.com/docs/4.2/facades#facade-class-reference
Frequently (especially when writing a library), I'll use constructor injection instead of facades to access these things. Here's an example:
use Illuminate\Config\Repository;
class SomeController {
private $config;
public function __construct(Repository $config) { $this->config = $config; }
public function getWhatever() { $value = $this->config->get('setting'); // Instead of Config::get('setting'); } }
I prefer this over facades, and over global functions like app()
, or even $this->app
, since it forces me to think about each object in terms of their actual dependencies.
But really, this is usually overkill. And like I said, I use this pattern mostly when writing libraries with service providers (which I do frequently at my job). In most cases in the context of the actual application code, however, I use facades pretty liberally.
I would probably create a trait for your models that you could add to anything that needs to be scoped based on the domain.
In the trait you set up a global scope for all queries for that model that limiting based on whatever you need.
I can't find the docs for Laravel 5.1, but here they are for 4.2 - http://laravel.com/docs/4.2/eloquent#global-scopes. You can check the SoftDeleting trait too
You could create a unique token (e.g. UUID) as a temporary reference for your images. Add the token value to the images (you could call the field ref_id
) and the form. After the article is saved, use the token to retrieve the images and replace it with the real article ID.
You'd also need some kind of process that periodically removes "stale" records (i.e. images that were created without the article being saved) from the images table. See Scheduling in the docs.
You could simplify this process by switching to UUIDs as your primary keys in the article model. This way you could create an article ID before it's being saved to the database. Check this article for an example.
hey, you can use a regex validation rule, see http://laravel.com/docs/5.1/validation#rule-regex
in your case, I reckon something like this will work like a charm
'myfield' => 'required|regex:/^.*P[0-9]+$/'
Question: You are trying to get this to work on what OS?
I found the thing that helped me the most was using vagrant and never trying to get php working with windows or even mac.
http://laravel.com/docs/4.2/homestead and https://puphpet.com/ are good places to start...
HTML/CSS and PHP serve two very different purposes. Bootstrap and Foundation are not templates but frameworks. They make common tasks easier but you still have to put it together. There are templates out there that utilize these frameworks though.
I'm not sure of which PHP Framework is the best as I've only used Laravel when it comes to frameworks. But I suggest you learn the basics of PHP first with resources like this or even basics in web development before diving into frameworks. Frameworks can make things a lot easier but it's good to actually know what it is the framework is helping with.
Laravel 5.1 does not include routes and views, as most people will end up customizing these to match their application anyway. The documentation still provides examples and direction for adding them back in yourself.
The idea is, since most people will modify them anyway, there's no sense in maintaining them in the code. And if you're not even using Laravel's auth, then they're discarded anyway. It's easier to maintain documentation on how to use the provided controllers, rather than a definitive implementation.
This is a similar reason why the Form/HTML helpers were removed -- they are very nice tools, but are not part of the framework or needed to have a Laravel application. By letting a third party support them, Laravel can keep focus on more critical parts of the framework.
That line is telling the application container that it should use the concrete class EloquentUserRepository
anywhere a UserContract
object is needed.
For example, take a look at Frontend/ProfileController.php
— the update
method asks for a UserContract
object called $user
. But where does that object come from?
The short answer is that the application container sees that the method needs a UserContract
, and uses the information passed through bind()
to create an instance of the EloquentUserRepository
, an object which implements the UserContract
interface. It then passes the new object to update
as the $user
parameter.
You can read more about the app container here: http://laravel.com/docs/5.0/container
Why do things this way? Well, it separates "how do I create a User Repository" from "using a User Repository to read information about users". ProfileController
doesn't care how a UserRepository
gets created, it just needs one to do its work. This makes the code shorter & less coupled, and hence easier to maintain.
Also, when it's time to test, it becomes dead simple to replace the EloquentUserRepository
with something else, which allows you to test the ProfileController
code without having to set up the rest of the application, connect it to a database, etc.
Hope that helps!
>Dropping some facades in favour of just straight up functions.
What you're referring to are helper functions, which is exactly what they are, helpers. Most of them don't contain any real logic and just defer to the classes you are referring to.
View::make will still work assuming you actually import it.
>Question 2: How was I supposed to know that that class isn't loaded by default anymore. For that matter, how am I supposed to know what class paths Request and Validator are found in? I just googled and found someone else with the same question.
Namespacing is a huge part of modern PHP, not understanding how that works is not the fault of Laravel.
If you want to know where certain classes are then just go to the API documentation enter the class you're looking for and find it.
As it says on the facades page that you linked, this is the class used by the example on the validation page:
However, you want to actually import the facade rather than the underlying class. All the facades are listed in your app.php config file in the 'aliases' array. So:
Illuminate\Support\Facades\Validator
If you want to make your life easier, use an IDE.
Do you have the correct cipher set? There was a switch in default cipher from version 4.1 to 4.2. (See the section about upgrading to 4.2: http://laravel.com/docs/5.0/upgrade) L5 probably use the new cipher unless you say otherwise.
Since you didn't specify which "4" version you're on, maybe it's the old one or you still use the old cipher in your L4.2 install?
the biggest backwords compatability break in laravel5 is their new filesystem, and they offer a legacy filesystem support feature so you can port your project over relatively easily.
That said, I started a project using Laravel 4.0 in march of 2013, nearly 2 years ago. I've upgraded it through each release with incredible ease, as each step has been documented for upgrading.
Also many of the older symfony2 releases are just as hard to upgrade as this one. Just look at the upgrade guide for going from 2.1 to 2.2. I fail to see how that's magically any better than the upgrade guide for laravel going from 4.2 to 5.0
Yeah, point both domains to the host and in Laravel you can use sub-domain routing.
Now it does say "sub-domain" but it does work on a full domain path as well: http://laravel.com/docs/4.2/routing#sub-domain-routing
Route::group(array('domain' => 'read-more.co.uk'), function() { /* routes here */ Route::get('/{link_slug}', 'Controller@something'); });
// other routes for the main site go below
If you are having a bunch of errors, you may be better off just setting up a virtual machin and starting from a clean slate. Not to mention, it will make it much easier when trying to mirror a production server.
The docs explain everything you need to get homestead up and running.
Take a look here: http://laravel.com/docs/4.2/homestead#installation-and-setup
Give that a go, and if you still can't get it working, shoot me a message and I'll do the best I can to help out!
If you're starting a new project, and it's a large scale website or web application - use Laravel.
In my opinion Laravel has taken everything that's great about other frameworks and put it on steroids. IMO there's nothing that can beat it.
Your previous experience in CodeIgniter would be a big plus as many things work similarly (Models, Controllers and Views).
Please take a look at Laracasts. I went down the Laravel path 6 months ago and I still feel like "I'm so lucky to be working with this framework"
Laravel seems like something up your alley. Learn more: http://laravel.com
Go through this: https://laracasts.com/series/laravel-from-scratch
This will definitely help you accomplish your idea.
You'll probably hear this alot, but try Laravel. Read the Laravel docs, and I guarantee you'll make a simple login/registration app by the end of the day.
I'd also recommend Laracasts, it's specifically tailored to Laravel and modern PHP development. (It is a paid resource, but at $9 p/m you can't go wrong) Try this Series: https://laracasts.com/series/build-a-laravel-app-from-scratch.
I maybe preaching for Laravel here, but if you're a beginner it's the best place to start, especially as it's so opinionated it'll push you towards best practices and a secure way of building a login/registration app easily.
Obviously go ahead and try other frameworks, but some can be pretty scary and generally throw people off. Laravel, however, is really nice to use.
P.s. Imo, you've probably posted this question in the wrong place, a better place to start would probably be /r/phphelp. But I'll still help you out as much as I can.
Resources: http://laravel.com/docs http://laracasts.com
Important point: Are you unable or just unwilling?
Being unable makes sense. Being unwilling means that this is posing itself as an opportunity to learn. If that's the case, I'd suggest take advantage of that opportunity and make use of the best tools available for whatever job you're working on. If this is the case, don't let the CLI scare you off. I like GUI myself, but sometimes you just gotta get down and dirty in that command line interface.
If you're unable, you may still be able to run migrations without the CLI, however if you can't find anything that does the job, maybe make something yourself. For example, take an existing CLI tool and execute it via passthru()
or exec()
(obviously security is going to be a major concern here).
That being said...
Have you tried Laravel, for example? In Laravel, I know what while you can call:
php artisan migrate:make name_your_migration_here
And
php artisan migrate
Apparently, you can call artisan commands from within PHP code, like so:
Artisan::call('command:name', array('argument' => 'foo', '--option' => 'bar'));
http://laravel.com/docs/commands#calling-other-commands
http://forumsarchive.laravel.io/viewtopic.php?id=5252
Note: I have not tried this. Let me know if this works for you.
Then again...
Even getting up and running using a modern framework like Larvel, or really, leveraging the power of PHP's composer
tool is really going to require you to use the CLI. So, if it's an "unable" situation (e.g. in production) then you'll be fine. If you're unwilling, you really need to learn.
By far the best way to do it would be using a view composer. To make it really simple you could set it up in the routes file. If your menu layout is the same across all views then you could do a @include('layouts.menu') then in your routes file you have
View::creator('layouts.menu', function($view) { $view->with('categories', Category::all()); });
Then the variable $categories will always be available in the menu which could foreach through it. You really don't want to do a eloquent call from a view
EDIT: Link to the docs for view composers http://laravel.com/docs/responses#view-composers
This an an awesome start for a school project. Drarok is right you need to move onto a frame work, it will make all the things you found painful in this project suddenly easier and leave you more time for development.
These tools have done all the authentication, separation of model, view and controller, routing and ton of other tools and saves you time designing and securing your own. Don't see this as a downside, more like standing on the shoulder of giants
Checkout laravel 4 which is very "cool" at the moment and very easy to get started with.
http://laravel.com/
>A Framework For Web Artisans
Laravel is a clean and classy framework for PHP web development. Freeing you from spaghetti code, Laravel helps you
create wonderful applications using simple, expressive syntax. Development should be a creative experience
that you enjoy, not something that is painful. Enjoy the fresh air.
The documentation is great, but you might find the bullet-points in this section particularly enlightening if you're looking to get an idea about what makes it different.
Well there are more way to "attack" this. As you mention python as a language you already speak, maybe check out flask. Its a python based framework for making the web part of a python project (routing included).
I my self use Laravel quite a lot - But that is a php framework that i guess in some ways could compare to flask.
If you can write and understand Java script a node express app could also be a possibility.
Happy coding!
I use the homestead vagrant box to run a VM. I then use cmder as my console tool to interact with the VM and use Git to push to BitBucket. Then simply push and pull from BitBucket as needed.
I would run homestead on all computers (Mac and PC) then it will make the workflow exactly the same across all systems.
Can also keep your custom homestead settings in git, so if you need to set up on a new computer just pull you homestead setup from git then pull any projects from git and you're good to go, simples.
Having more than 4-5 dependencies is a pretty major code smell, having 10+ dependencies means you are almost guaranteed to be lacking some abstraction and you should be trying to refactor to something better immediately.
Your method of providing dependencies (as public properties) breaks encapsulation, makes construction of the object extremely cumbersome and creates a horrible to use API. Requiring you to set all these dependencies before using the class is not clear at all, whereas only declaring a constructor that needs these parameters makes it very explicit. Remember, you want to write code that other people understand, and by "other people" I'm also referring to you when you come back to look it in 6 months.
You are trying to make a point about requiring a long comment block when instantiating ClassA in the final example but why does that need a comment block? You are instantiating a class and providing it with it's dependencies, this is explained through code instead of through a comment which is always the preferable option.
I would really recommend looking into service/IoC containers, they handle the construction of these objects for you. So using a container, you would actually do something like:
$obj = $container->make(ClassA::class);
It's a pretty big topic but you could start with the docs for Laravel's service container. Implementing DI without one can be a major pain in the ass.
Can you use polymorphic relations, or are the foreign keys unrelated to each other, or maybe you need to have the constraint?
I am sorry I find the docs to be impenetrable and for the most part useless unless you already know what's going on.
I'm just a bad programmer and bad programmers shouldn't use Laravel! I'll just stick to frameworks with... Code examples! And plain english explanations of what the fuck is supposed to be happening! Shame on me for wanting more!
edit: I'll use your example, as an example.
I randomly drilled down into a page from your link: http://laravel.com/api/5.1/Illuminate/Database/Eloquent/MassAssignmentException.html
MassAssignmentException
class MassAssignmentException extends RuntimeException (View source)
That's all you get! Thanks!
The boot
method is run "...after all other service providers have been registered, meaning you have access to all other services that have been registered by the framework" (http://laravel.com/docs/5.1/providers#the-boot-method) Frequent use case: binding ViewComposers, event listeners, routes.
The register
method is meant to register your bindings in the service container. (http://laravel.com/docs/5.1/providers#the-register-method)
The docs are your friend. ;)
+1 to getting Twig it's definitely worth it. However you can extend blade but not sure how close it is to actually what you want.
If you're looking for live filtering when your best bet is javascript, there is a simple jQuery snippit that might do what you want.
Could you expand what you mean by a filter, because what you've displayed is more like a directive.
Because the relationship is a belongsToMany
, it's returning a collection of Permissions
items. You will need to check if the collection has an item with the appropriate id
. For example:
if (! $request->user()->permissions->keyBy('id')->has(1)) { // Redirect }
The <code>keyBy</code> method takes the name of the column we want to identify each item with (id
in this case) and sets the key in the array to the value of that column, and <code>has</code> checks to see if an item with the supplied key (the id
) exists in the collection.
If you must cache (altho look at optimizing your queries first - most probably eager loading) there are eloquent query chachings available.
http://laravel.com/docs/4.2/queries#caching-queries
altho this is 4.2, i think its still available in 5.1. I don't know why they would remove it.
You can also tag caches, so you could tag the french lacalisation, and if the french changes, you can clear just that cache.
Note that tagged caching doesnt work with DB or filesystem caching.
The caches are also specific to that query. So if anything in that cached query is really dynamic, there will be a lot of cache misses & bloatings.
I think you might be looking at this the wrong way. You can use middleware to locate the request's user, but applying global eloquent modifiers from this point would be brittle at best (not sure if that is even possible).
I would instead recommend creating a query scope on any relevant models that need to be restricted. It would require making changes to several eloquent queries, but the behaviour becoems more explicit and it prevents you from accidentally modifying the wrong queries. Something like:
//in your Order model public function scopeByUserLocation($q, User $user){ if(!$user->isAdmin()){ $q->where('location_id', $user->location_id); } } // in your controller action $orders = Order:byUserLocation($request->user())->get();
> the problem I had is that I had to load all libraries framework use even though some functionality was not used
How come? Composer usually just loads on-demand. Sounds like you've created a weird unnecessary abstraction layer on top of composer with your ini files.
Also, for schemas, people usually use incremental migration scripts. Laravel's migrations work like this, for inspiration: http://laravel.com/docs/5.1/migrations
I use the API docs to dig deeper into the functionality of something, like if I need to do something that isn't addressed specifically in the regular documentation but I'm sure there's a way to do it.
For example, I look at the API docs for TestCase all the time, because there are a number of methods available that aren't shown in the docs.
If you're using a form request, then you can conditionally set the rules based on the HTTP method by checking the string value of $this->method()
.
For example:
public function rules() { $rules = [ 'field1' => ['string', 'max:32'], ];
if ($this->method() == 'POST') { $rules['field1'][] = 'required'; }
return $rules; }
If you want more structure, write smaller Controller methods. E.g. by:
Write commands like here: http://laravel.com/docs/5.1/queues#writing-job-classes (Leave away traits and just implement "SelfHandling")
and call them via Bus::dispatch(new NameOfCommand()); in your controller.
Described here: http://laravel.com/docs/5.1/validation#form-request-validation
Create a folder "Components" Create a component-folder for each component and everything this component has
Component/User
Component/User/Commands
Component/User/Events
Component/User/Handlers
Component/User/Models
So try moving away from a big Models folder and start writing components which makes your code much more loose, decoupled and reusable.
Just want to clarify for others, OP is talking about the Homestead installation process, not the Laravel installation process.
OP: If you don't know how to get a basic environment set up, and are reliant on Homestead to do that for you, I'm afraid that there's no simple way to try out any modern framework. It's not Laravel's fault or the documentation's fault, it's that you need to become more familiar with either setting up your own WAMP environment, or using Virtualbox + Vagrant.
The actual installation process for Laravel is quite straight-forward, provided you have all the pieces to create a local environment in place.
http://laravel.com/docs/5.1/installation
All that said, I do sympathize with you. Setting up local environments (especially on Windows) is a huge pain in the ass.
You can also access the api documentation ( http://laravel.com/api/5.1/ ) and search for the class name.
Then you can see all the methods.
A little bit of tinkering (or a basic test route) you can dd(); the result and see what it looks like.
Also, use the search on laravel docs more generically.
Instead on $errors-≥all(); search for errors or validation.
Then read the page (or ctrl+f to narrow things down)
http://laravel.com/docs/5.1/validation#working-with-error-messages
Is what you're looking for I think. There are cases where you'll come across an undocumented function, if it's not very descriptive in itself I tend to dive into the classes in PHPstorm (CMD+CLICK) to read over them.
Hope that helps!!